翻转一棵二叉树
来源:互联网 发布:安装linux的步骤 编辑:程序博客网 时间:2024/05/01 22:41
1 1 / \ / \2 3 => 3 2 / \ 4 4
递归固然可行,能否写个非递归的?
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
public void invertBinaryTree(TreeNode root) {
// write your code here
/*递归方法
if(root==null)
return;
TreeNode temp = root.left;
root.left=root.right;
root.right=temp;
invertBinaryTree(root.left);
invertBinaryTree(root.right);*/
//非递归
if (root==null)
return;
Queue<TreeNode> q = new LinkedList<TreeNode>();//队列
q.offer(root);//入队,添加元素
TreeNode node = q.poll();//取出队列首元素
while (node!=null) {
TreeNode temp = node.left;
node.left=node.right;
node.right=temp;
if (node.left!=null)
q.offer(node.left);
if (node.right!=null)
q.offer(node.right);
node = q.poll();
}
}
}
- 翻转一棵二叉树
- 翻转一棵二叉树 + Java中queue的总结
- 【每日一题-11】求二叉树高度/销毁一棵二叉树与链表翻转
- C++二叉树翻转
- 翻转二叉树
- 翻转二叉树
- 题目:翻转二叉树
- LintCode 翻转二叉树
- LinkCode-翻转二叉树
- 翻转二叉树
- 翻转二叉树
- 翻转二叉树
- LintCode_175_翻转二叉树
- 二叉树翻转
- lintcode ----翻转二叉树
- lintcode,翻转二叉树
- 翻转二叉树
- 翻转二叉树
- 压力测试——测试MySQL
- ADB授权原理
- 使用Android的draw9patch制作点9图
- 用一部极客电影让你感受互联网科技的潜力
- Bay_Area_Bike_Share_Analysis
- 翻转一棵二叉树
- 软件工程之软件设计(2)
- Android项目包名命名规范及常见项目架构
- 搭建个人网站
- [BZOJ1754]牛的数学
- 随机变量及概率分布
- Java web开发中的乱码问题
- GitHub和Git多人协作开发
- MySQL 数据备份与还原