Description
<nav class="tab-view hide-scrollbar" style="box-sizing: border-box; display: block; overflow-y: hidden; overflow-x: auto; white-space: nowrap; margin-top: 32px;">olution</nav>
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]
Output: return the root of the binary tree [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:
The above binary tree is serialized as [1,2,3,#,#,4,#,#,5]
.
Solution
Recursion, time O(n), space O(n)
研究了好半天才明白这道题是什么意思....
首先这棵树是左倾斜的,呈一把梳子的形状,然后题目需要把树顺时针翻转,变成这样:
对左子树进行递归即可,因为右子树要么为空要么是叶子节点。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode upsideDownBinaryTree(TreeNode root) {
if (root == null || (root.left == null && root.right == null)) {
return root;
}
TreeNode newRoot = upsideDownBinaryTree(root.left);
root.left.left = root.right;
root.left.right = root;
root.left = null;
root.right = null;
return newRoot;
}
}
Iteration, time O(n), space O(1)
图中的temp我这里命名为right,更好理解。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode upsideDownBinaryTree(TreeNode root) {
TreeNode prev = null;
TreeNode curr = root;
TreeNode right = null;
while (curr != null) {
TreeNode next = curr.left;
curr.left = right;
right = curr.right;
curr.right = prev;
prev = curr;
curr = next;
}
return prev;
}
}