Problem
Invert a binary tree.
Example:
Input: 4 / 2 7 / / 1 3 6 9 Output: 4 / 7 2 / / 9 6 3 1
Trivia:
This problem was inspired by this original tweet by Max Howell:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f*** off.Solution Recursive
class Solution { public TreeNode invertTree(TreeNode root) { if (root == null) return root; TreeNode left = invertTree(root.left); TreeNode right = invertTree(root.right); root.left = right; root.right = left; return root; } }Iterative
class Solution { public TreeNode invertTree(TreeNode root) { if (root == null) return root; Queuequeue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { TreeNode node = queue.poll(); TreeNode left = node.left; node.left = node.right; node.right = left; if (node.left != null) queue.offer(node.left); if (node.right != null) queue.offer(node.right); } return root; } }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://www.ezyhdfw.cn/yun/71793.html
摘要:題目鏈接題目分析反轉(zhuǎn)二叉樹(shù)。思路類似反轉(zhuǎn)兩個(gè)變量,先把左右子樹(shù)存進(jìn)單獨(dú)的變量,再相互覆蓋左右子樹(shù)。并對(duì)子樹(shù)進(jìn)行相同的操作。最終代碼若覺(jué)得本文章對(duì)你有用,歡迎用愛(ài)發(fā)電資助。 D59 226. Invert Binary Tree 題目鏈接 226. Invert Binary Tree 題目分析 反轉(zhuǎn)二叉樹(shù)。 思路 類似反轉(zhuǎn)兩個(gè)變量,先把左右子樹(shù)存進(jìn)單獨(dú)的變量,再相互覆蓋左右子樹(shù)。 并...
摘要:算法思路判斷樹(shù)是否為空同時(shí)也是終止條件。分別對(duì)左右子樹(shù)進(jìn)行遞歸。代碼實(shí)現(xiàn)判斷當(dāng)前樹(shù)是否為左右子樹(shù)結(jié)點(diǎn)交換分別對(duì)左右子樹(shù)進(jìn)行遞歸返回樹(shù)的根節(jié)點(diǎn)歡迎一起加入到開(kāi)源倉(cāng)庫(kù),可以向提交您其他語(yǔ)言的代碼。 Time:2019/4/21Title: Invert Binary TreeDifficulty: EasyAuthor: 小鹿 題目:Invert Binary Tree(反轉(zhuǎn)二叉樹(shù)) ...
摘要:題目鏈接思路如果需要反轉(zhuǎn)一個(gè)二叉樹(shù),那么我們需要遍歷整個(gè)樹(shù)的所有節(jié)點(diǎn)。這兩種辦法分別可以用迭代或者遞歸的辦法實(shí)現(xiàn)。算法復(fù)雜度遞歸時(shí)間空間時(shí)間空間代碼遞歸 題目鏈接:Invert Binary Tree 思路:如果需要反轉(zhuǎn)一個(gè)二叉樹(shù),那么我們需要遍歷整個(gè)樹(shù)的所有節(jié)點(diǎn)。如果想遍歷所有的節(jié)點(diǎn),我們可以用Depth First Search(DFS)或者Breadth First Search...
摘要:原題鏈接遞歸法復(fù)雜度時(shí)間空間遞歸??臻g思路這個(gè)難倒大神的題也是非常經(jīng)典的一道測(cè)試對(duì)二叉樹(shù)遍歷理解的題。遞歸的終止條件是當(dāng)遇到空節(jié)點(diǎn)或葉子節(jié)點(diǎn)時(shí),不再交換,直接返回該節(jié)點(diǎn)。代碼給出的是后序遍歷的自下而上的交換,先序遍歷的話就是自上而下的交換。 Invert Binary Tree Invert a binary tree. 4 / 2 7 / ...
摘要:微信公眾號(hào)記錄截圖記錄截圖目前關(guān)于這塊算法與數(shù)據(jù)結(jié)構(gòu)的安排前。已攻略返回目錄目前已攻略篇文章。會(huì)根據(jù)題解以及留言內(nèi)容,進(jìn)行補(bǔ)充,并添加上提供題解的小伙伴的昵稱和地址。本許可協(xié)議授權(quán)之外的使用權(quán)限可以從處獲得。 Create by jsliang on 2019-07-15 11:54:45 Recently revised in 2019-07-15 15:25:25 一 目錄 不...
閱讀 3156·2021-08-03 14:05
閱讀 2210·2019-08-29 15:35
閱讀 733·2019-08-29 13:30
閱讀 3234·2019-08-29 13:20
閱讀 2589·2019-08-23 18:15
閱讀 1855·2019-08-23 14:57
閱讀 2280·2019-08-23 13:57
閱讀 1396·2019-08-23 12:10