Leetcode Binary Tree Upside Down
2016-06-07 21:39
323 查看
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.
For example:
Given a binary tree
return the root of the binary tree
Difficulty: Medium
Solution: From bottom to up, use recursion.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
TreeNode ans = null;
public void helper(TreeNode root){
if(root == null)
return;
TreeNode leftNode = root.left;
TreeNode rightNode = root.right;
if(leftNode == null){
ans = root;
return;
}
helper(leftNode);
leftNode.left = rightNode;
leftNode.right = root;
root.left = null;
root.right = null;
}
public TreeNode upsideDownBinaryTree(TreeNode root) {
helper(root);
return ans;
}
}
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
Difficulty: Medium
Solution: From bottom to up, use recursion.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
TreeNode ans = null;
public void helper(TreeNode root){
if(root == null)
return;
TreeNode leftNode = root.left;
TreeNode rightNode = root.right;
if(leftNode == null){
ans = root;
return;
}
helper(leftNode);
leftNode.left = rightNode;
leftNode.right = root;
root.left = null;
root.right = null;
}
public TreeNode upsideDownBinaryTree(TreeNode root) {
helper(root);
return ans;
}
}
相关文章推荐
- C/C++ 中缀表达式转换成后缀表达式并求值
- 多线程和多进程的区别(小结)
- Maven内置变量说明:
- telnet、ssh配置信息
- jquery与php交互之GET、 POST
- Struts2源码分析——StrutsPrepareAndExecuteFilter
- javaweb学习总结(四十五)——监听器(Listener)学习二
- 旅游队参加省赛的总结
- gdb调试多进程和多线程程序
- java读取文件 每行首字丢失问题
- 凹数科技笔试
- HDU1002(高精度计算)
- 运维工程师到底在作什么?从何学起,掌握哪些知识?
- 内联函数和宏定义的区别
- java中util.Date和数据库中datetime的操作!
- 汉诺塔问题小结
- 第二次冲刺第十天
- iOS 开发技巧收藏贴 链接整理
- [转]TIME类的运算符重载
- sublime上的JS代码提示2---api