【leetcode】【Easy】【226. Invert Binary Tree】【tree】
来源:互联网 发布:存档软件 编辑:程序博客网 时间:2024/04/19 07:46
problem link
code:
code1:递归在leetcode上要比BFS快一点
public class Solution { public TreeNode invertTree(TreeNode root) { if(root == null) return null; TreeNode tmp = root.left; root.left = invertTree(root.right); root.right = invertTree(tmp); return root; }}
code2:BFS遍历整个树,比递归慢
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public TreeNode invertTree(TreeNode root) { if(root==null) return null; Queue<TreeNode> queue=new LinkedList<TreeNode>(); queue.offer(root); while(!queue.isEmpty()){ TreeNode cur=queue.poll(); //要考虑左右子树是否存在 if(cur.left==null && cur.right!=null){//只存在右子树 cur.left=cur.right; cur.right=null; queue.offer(cur.left); }else if(cur.right==null && cur.left!=null){//只存在左子树 cur.right=cur.left; cur.left=null; queue.offer(cur.right); }else if(cur.left!=null && cur.right!=null){//左右子树都存在 TreeNode temp=cur.left; cur.left=cur.right; cur.right=temp; queue.offer(cur.left); queue.offer(cur.right); }//左右子树都不存在不用操作 } return root; }}
while循环中的判断可以简化。
但是不懂为什么下面三行不会报NullPointerException??
TreeNode temp=cur.left;cur.left=cur.right;cur.right=temp;
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public TreeNode invertTree(TreeNode root) { if(root==null) return null; Queue<TreeNode> queue=new LinkedList<TreeNode>(); queue.offer(root); while(!queue.isEmpty()){ TreeNode cur=queue.poll(); TreeNode temp=cur.left; cur.left=cur.right; cur.right=temp; if(cur.left!=null){ queue.offer(cur.left); } if(cur.right!=null){ queue.offer(cur.right); } } return root; }}
0 0
- 【leetcode】【Easy】【226. Invert Binary Tree】【tree】
- Leetcode 226. Invert Binary Tree (Easy) (cpp)
- LeetCode 226. Invert Binary Tree (Easy)
- 226. Invert Binary Tree (Easy)
- Invert Binary Tree(easy)
- [Leetcode 226, Easy] Invert Binary Tree
- <LeetCode><Easy>226Invert a binary tree
- LeetCode #226 - Invert Binary Tree - Easy
- 【Leetcode-easy-226】Invert Binary Tree
- 226.leetcode Invert Binary Tree(easy)[二叉树 递归]
- LeetCode 226. Invert Binary Tree
- [leetcode] 226.Invert Binary Tree
- [leetcode] 226. Invert Binary Tree
- 【LeetCode】226. Invert Binary Tree
- leetCode 226. Invert Binary Tree
- LeetCode #226. Invert Binary Tree
- [LeetCode]226. Invert Binary Tree
- 226. Invert Binary Tree LeetCode
- 斯坦福机器学习公开课随笔1,2
- LeetCode--485. Max Consecutive Ones
- NPOI导出多张图片到Excel
- Python collection的使用
- bootstrap——js插件(一、modal)
- 【leetcode】【Easy】【226. Invert Binary Tree】【tree】
- EAS客户端 开启编辑单据时开启历史记录的方式
- 利用wsdl文件生成webservice接口的java客户端测试代码
- Java基础-java.sql.ResultSet的getDate获取时间中时分秒为0的问题
- 关于设计模式一点使用心得
- JS判断客户端是否是iOS或者Android手机移动端
- win10 免安装版本的MySQL的下载安装和配置
- c#获取外网IP代码片段
- Unity3D 集成 高德地图SDK 地图