LeetCode-Invert Binary Tree
来源:互联网 发布:如何分析数据spss 编辑:程序博客网 时间:2024/06/05 10:55
tree一般就用recursion 还需要继续练习
需要注意的是recursion总是和循环写混乱,并不需要loop了
最开始我把if写成了while
public class Solution { public TreeNode invertTree(TreeNode root) { if ( root == null ) return null; if ( root.left != null || root.right != null ){ TreeNode temp = root.left; root.left = root.right; root.right = temp; invertTree( root.left ); invertTree( root.right ); } return root; }}记住先要判断root是不是null再访问它的left right
The above solution is correct, but it is also bound to the application stack, which means that it's no so much scalable - (you can find the problem size that will overflow the stack and crash your application), so more robust solution would be to use stack data structure.
public class Solution { public TreeNode invertTree(TreeNode root) { if (root == null) { return null; } final Deque<TreeNode> stack = new LinkedList<>(); stack.push(root); while(!stack.isEmpty()) { final TreeNode node = stack.pop(); final TreeNode
//BFS <pre name="code" class="java">public class Solution { public TreeNode invertTree(TreeNode root) { if (root == null) { return null; } final Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); while(!queue.isEmpty()) { final TreeNode node = queue.poll(); final TreeNode left = node.left; node.left = node.right; node.right = left; if(node.left != null) { queue.offer(node.left); } if(node.right != null) { queue.offer(node.right); } } return root; }}
left = node.left; node.left = node.right; node.right = left; if(node.left != null) { stack.push(node.left); } if(node.right != null) { stack.push(node.right); } } return root; }}
Finally we can easly convert the above solution to BFS - or so called level order traversal.
0 0
- [leetcode] Invert Binary Tree
- [LeetCode]Invert Binary Tree
- leetcode:Invert Binary Tree
- LeetCode Invert Binary Tree
- LeetCode | Invert Binary Tree
- leetcode--Invert Binary Tree
- [leetcode] Invert Binary Tree
- [LeetCode] Invert Binary Tree
- LeetCode Invert Binary Tree
- leetcode : Invert Binary Tree
- [LeetCode] Invert Binary Tree
- [Leetcode]Invert Binary Tree
- LeetCode: Invert Binary Tree
- LeetCode Invert Binary Tree
- leetcode: Invert Binary Tree
- LeetCode Invert Binary Tree
- LeetCode || Invert Binary Tree
- LeetCode:Invert Binary Tree
- 使用java的DBUtils
- I/O流与异常
- Flume前述
- iOS开发常用国外网站清单
- ajax 上传图片预览
- LeetCode-Invert Binary Tree
- 苹果官方制作MAC OS的启动U盘的步骤
- CI框架 CodeIgniter 伪静态 htaccess设置和Nginx伪静态方法
- HTML表单·表格标签
- 2.1小测验3解析-线性表的指针不能用++
- Linux(Fedora)学习使用之gnome-shell
- XHTML表格总结
- ios 微信浏览器中 触发webkitTransitionEnd 问题
- 遇到的面试题:html和javascript