Binary Tree Upside DownTotal Accepted:
813 Total Submissions:
2515
Given a binary tree where all the right nodes is either leaf nodes with a sibling (a left node that shares the same paren T node) or empty, flip it upside down and turn it to a tree where the original right nodes turned to left leaf nodes. Return the new root.
For example:
Given a binary tree
{1,2,3,4,5}
,
1 / 2 3/4 5
Return the root of the binary tree [4,5,2,#,#,3,1]
.
4 / 5 2 / 3 1
Confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
Analysis
Understand the definition of this tree, the answer is self-evident.
Note
None
[CODE]
/** * Definition for Binary tree * public class TreeNode {* int val, * TreeNode left, * TreeNode right; *
treenode (int x) {val = x;} *} */public class Solution {public TreeNode upsidedownbinarytree (TreeNode root) { stack<treenode> stack = new stack<treenode> (); if (root==null) return null; while (root.left! = null) {Stack.push (root); root=root.left;} Stack.push (root); while (!stack.empty ()) { TreeNode node = Stack.pop (); if (!stack.empty ()) { node.right = Stack.peek (); Node.left = Stack.peek (). right; } else { node.left = null; Node.right = null; } } return root; }}
Leetcode 156:binary Tree Upside down