Binary Tree Upside Down
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 Last updated
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 Last updated
1
/ \
2 3
/
4
\
5/**
* 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)
return null;
TreeNode cur = root, tmp = null, next = null,pre = null;
while(cur != null){
next = cur.left;
cur.left = tmp;
tmp = cur.right;
cur.right = pre;
pre= cur;
cur = next;
}
return pre;
}
}