[LeetCode 156] Binary Tree Upside Down
2015-09-25 14:59
253 查看
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
solution:
use stack to store left node from top to bottom, then reverse to construct the tree.
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
solution:
use stack to store left node from top to bottom, then reverse to construct the tree.
if(root ==null || (root.left == null && root.right == null)) return root; Stack<TreeNode> path = new Stack<>(); while(root.left!=null) { path.add(root); root = root.left; } path.add(root); while(!path.isEmpty()) { TreeNode temp = path.pop(); if(!path.isEmpty()) { temp.right = path.peek(); temp.left = path.peek().right; }else{ temp.right = null; temp.left = null; } } return root;
相关文章推荐
- Chrome浏览器扩展开发系列之十一:NPAPI插件的使用
- 在CentOS下面编译WizNote Qt Project
- 如何在 Linux 中整理磁盘碎片
- 如何在 Linux 中整理磁盘碎片
- 十个PHP高级应用技巧果断收藏
- Nginx作为web服务器的安装配置
- html5 ajax Java接口 上传图片
- GCD下载图片
- 流式编程的的几个实例
- C++ 嵌套类使用(三)
- monkeyrunner 自动化测试 图片对比的实现
- 数据库的知识
- [计划任务 - Linux]三分钟学会cron
- Java基础知识强化86:BigInteger类之BigInteger概述和构造方法
- 遥感数据下载地址
- Several ports (8005, 8080, 8009) required by Tomcat v7.0 Server at localhost are解决方法
- Linux日志文件
- spring中文乱码问题
- Failed to load JavaHL Library解决方法
- ssh: connect to host github.com port 22: Connection refused