C++實(shí)現(xiàn)LeetCode(156.二叉樹的上下顛倒)
[LeetCode] 156. Binary Tree Upside Down 二叉樹的上下顛倒
Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes. Return the new root.
Example:
Input: [1,2,3,4,5]
1
/ \
2 3
/ \
4 5Output: return the root of the binary tree [4,5,2,#,#,3,1]
4
/ \
5 2
/ \
3 1
Clarification:
Confused what [4,5,2,#,#,3,1] means? Read more below on how binary tree is serialized on OJ.
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1
/ \
2 3
/
4
\
5
The above binary tree is serialized as [1,2,3,#,#,4,#,#,5].
這道題讓我們把一棵二叉樹上下顛倒一下,而且限制了右節(jié)點(diǎn)要么為空要么一定會有對應(yīng)的左節(jié)點(diǎn)。上下顛倒后原來二叉樹的最左子節(jié)點(diǎn)變成了根節(jié)點(diǎn),其對應(yīng)的右節(jié)點(diǎn)變成了其左子節(jié)點(diǎn),其父節(jié)點(diǎn)變成了其右子節(jié)點(diǎn),相當(dāng)于順時針旋轉(zhuǎn)了一下。對于一般樹的題都會有迭代和遞歸兩種解法,這道題也不例外,先來看看遞歸的解法。對于一個根節(jié)點(diǎn)來說,目標(biāo)是將其左子節(jié)點(diǎn)變?yōu)楦?jié)點(diǎn),右子節(jié)點(diǎn)變?yōu)樽笞庸?jié)點(diǎn),原根節(jié)點(diǎn)變?yōu)橛易庸?jié)點(diǎn),首先判斷這個根節(jié)點(diǎn)是否存在,且其有沒有左子節(jié)點(diǎn),如果不滿足這兩個條件的話,直接返回即可,不需要翻轉(zhuǎn)操作。那么不停的對左子節(jié)點(diǎn)調(diào)用遞歸函數(shù),直到到達(dá)最左子節(jié)點(diǎn)開始翻轉(zhuǎn),翻轉(zhuǎn)好最左子節(jié)點(diǎn)后,開始回到上一個左子節(jié)點(diǎn)繼續(xù)翻轉(zhuǎn)即可,直至翻轉(zhuǎn)完整棵樹,參見代碼如下:
解法一:
class Solution { public: TreeNode *upsideDownBinaryTree(TreeNode *root) { if (!root || !root->left) return root; TreeNode *l = root->left, *r = root->right; TreeNode *res = upsideDownBinaryTree(l); l->left = r; l->right = root; root->left = NULL; root->right = NULL; return res; } };
下面我們來看迭代的方法,和遞歸方法相反的時,這個是從上往下開始翻轉(zhuǎn),直至翻轉(zhuǎn)到最左子節(jié)點(diǎn),參見代碼如下:
解法二:
class Solution { public: TreeNode *upsideDownBinaryTree(TreeNode *root) { TreeNode *cur = root, *pre = NULL, *next = NULL, *tmp = NULL; while (cur) { next = cur->left; cur->left = tmp; tmp = cur->right; cur->right = pre; pre = cur; cur = next; } return pre; } };
Github 同步地址:
https://github.com/grandyang/leetcode/issues/156
類似題目:
參考資料:
https://leetcode.com/problems/binary-tree-upside-down/
https://leetcode.com/problems/binary-tree-upside-down/discuss/49412/Clean-Java-solution
到此這篇關(guān)于C++實(shí)現(xiàn)LeetCode(156.二叉樹的上下顛倒)的文章就介紹到這了,更多相關(guān)C++實(shí)現(xiàn)二叉樹的上下顛倒內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++實(shí)現(xiàn)LeetCode(187.求重復(fù)的DNA序列)
這篇文章主要介紹了C++實(shí)現(xiàn)LeetCode(187.求重復(fù)的DNA序列),本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07C++數(shù)據(jù)模型應(yīng)用在QML委托代理機(jī)制中
這篇文章主要介紹了在QML委托代理機(jī)制中使用C++數(shù)據(jù)模型,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08C語言光標(biāo)旋轉(zhuǎn)與倒計時功能實(shí)現(xiàn)示例詳解
這篇文章主要為大家介紹了C語言實(shí)現(xiàn)光標(biāo)旋轉(zhuǎn)與倒計時功能的示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步早日升職加薪2021-11-11