C++實現(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é)點要么為空要么一定會有對應的左節(jié)點。上下顛倒后原來二叉樹的最左子節(jié)點變成了根節(jié)點,其對應的右節(jié)點變成了其左子節(jié)點,其父節(jié)點變成了其右子節(jié)點,相當于順時針旋轉了一下。對于一般樹的題都會有迭代和遞歸兩種解法,這道題也不例外,先來看看遞歸的解法。對于一個根節(jié)點來說,目標是將其左子節(jié)點變?yōu)楦?jié)點,右子節(jié)點變?yōu)樽笞庸?jié)點,原根節(jié)點變?yōu)橛易庸?jié)點,首先判斷這個根節(jié)點是否存在,且其有沒有左子節(jié)點,如果不滿足這兩個條件的話,直接返回即可,不需要翻轉操作。那么不停的對左子節(jié)點調用遞歸函數,直到到達最左子節(jié)點開始翻轉,翻轉好最左子節(jié)點后,開始回到上一個左子節(jié)點繼續(xù)翻轉即可,直至翻轉完整棵樹,參見代碼如下:
解法一:
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; } };
下面我們來看迭代的方法,和遞歸方法相反的時,這個是從上往下開始翻轉,直至翻轉到最左子節(jié)點,參見代碼如下:
解法二:
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
到此這篇關于C++實現(xiàn)LeetCode(156.二叉樹的上下顛倒)的文章就介紹到這了,更多相關C++實現(xiàn)二叉樹的上下顛倒內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C++實現(xiàn)LeetCode(187.求重復的DNA序列)
這篇文章主要介紹了C++實現(xiàn)LeetCode(187.求重復的DNA序列),本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內容,需要的朋友可以參考下2021-07-07