226. Invert Binary Tree
来源:互联网 发布:深蓝知乎 编辑:程序博客网 时间:2024/06/05 20:14
递归方法:
public TreeNode invertTree(TreeNode root) {TreeNode m;
if(root==null){
return root;
}
else if(root.left==null&&root.right==null){
return root;
}
m=invertTree(root.left);
root.left=invertTree(root.right);
root.right=m;
return root;
}
迭代方法:
public TreeNode invertTree(TreeNode root) {
if(root==null){
return root;
}
TreeNode m=null;
TreeNode root1=null;
Queue<TreeNode> queue = new LinkedList();
queue.offer(root);
while(!queue.isEmpty()){
root1=queue.poll();
if(root1.left!=null){
queue.offer(root1.left);
}
if(root1.right!=null){
queue.offer(root1.right);
}
m=root1.left;
root1.left=root1.right;
root1.right=m;
}
return root;
}
写迭代方法的时候 while写成了if 自己看了好几遍没看出来
0 0
- 226.Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 常用的实用工具jar包导入
- 分布式定时任务框架-Elastic Job
- DataCenter 数据中心
- 死锁
- 72. Edit Distance
- 226. Invert Binary Tree
- 你不知道的Java学习笔记15--StringBuffer类
- Lucene学习教程——Lucene索引创建
- android中ArrayList源码分析
- mysql5.5全备份的问题(- Warning: Skipping the data of table mysql.event. Specify the --events option expli)
- CODEVS 2072 分配房间
- spark如何划分stage
- centos下安装git
- Android属性动画(二)——ValueAnimator