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 5 Output: 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]
.
這道題讓我們把一棵二叉樹上下顛倒一下,而且限制了右節點要么為空要么一定會有對應的左節點。上下顛倒后原來二叉樹的最左子節點變成了根節點,其對應的右節點變成了其左子節點,其父節點變成了其右子節點,相當於順時針旋轉了一下。對於一般樹的題都會有迭代和遞歸兩種解法,這道題也不例外,先來看看遞歸的解法。對於一個根節點來說,目標是將其左子節點變為根節點,右子節點變為左子節點,原根節點變為右子節點,首先判斷這個根節點是否存在,且其有沒有左子節點,如果不滿足這兩個條件的話,直接返回即可,不需要翻轉操作。那么不停的對左子節點調用遞歸函數,直到到達最左子節點開始翻轉,翻轉好最左子節點后,開始回到上一個左子節點繼續翻轉即可,直至翻轉完整棵樹,參見代碼如下:
解法一:
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; } };
下面我們來看迭代的方法,和遞歸方法相反的時,這個是從上往下開始翻轉,直至翻轉到最左子節點,參見代碼如下:
解法二:
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