翻转二叉树
来源:互联网 发布:程序员一天工作几小时 编辑:程序博客网 时间:2024/05/21 02:53
翻转一棵二叉树
样例
1 1 / \ / \2 3 => 3 2 / \ 4 4
挑战
递归固然可行,能否写个非递归的?
/** * 翻转一棵二叉树 * 递归法 * 1. 当前节点为空,直接返回 * 2. 当前节点不为空,交换左右节点 * 3. 分别对左右子树做同样的操作 * * @param root */ public void invertBinaryTree1(TreeNode root) { if (root == null) return; if (root.left != null && root.right == null) { root.right = root.left; root.left = null; } else if (root.left == null && root.right != null) { root.left = root.right; root.right = null; } else if (root.left != null && root.right != null) { TreeNode p = root.left; root.left = root.right; root.right = p; } invertBinaryTree1(root.left); invertBinaryTree1(root.right); } /** * 非递归 * 将根节点放入栈中,然后不断取出节点,交换该节点的左右儿子,并把左右儿子放入栈中,不断重复,直到栈为空 * * @param root */ public void invertBinaryTree(TreeNode root) { if (root == null) return; Stack<TreeNode> stack = new Stack<>(); stack.push(root); TreeNode p = root, q = null; while (!stack.empty()) { p = stack.pop(); q = p.left; p.left = p.right; p.right = q; if (p.right != null) { stack.push(p.right); } if (p.left != null) { stack.push(p.left); } } }
阅读全文
0 0
- C++二叉树翻转
- 翻转二叉树
- 翻转二叉树
- 题目:翻转二叉树
- LintCode 翻转二叉树
- LinkCode-翻转二叉树
- 翻转二叉树
- 翻转二叉树
- 翻转二叉树
- LintCode_175_翻转二叉树
- 二叉树翻转
- lintcode ----翻转二叉树
- lintcode,翻转二叉树
- 翻转二叉树
- 翻转二叉树
- 翻转二叉树
- 翻转二叉树
- LintCode-翻转二叉树
- Spring中常用注解的区别和作用
- email 定时任务xml设置
- str不能为null
- VS产生sdf和ipch文件太大处理方案
- Android捕捉未捕捉的异常
- 翻转二叉树
- 设计模式之享元模式
- lintcode 整数排序 II | 快速排序(Java)
- web 学习笔记12-JSP技术
- 【剑指offer】用两个栈实现队列
- Exception in thread “main” java.lang.UnsupportedClassVersionError: com/crunchify/Main : Unsupported
- 工厂模式
- 代码之髓读后感——关于学习
- 链表(单向、双向、单向循环、双向循环)学习过程总结——有源代码、注释和示意图