- 翻转二叉树
翻转一棵二叉树。
示例:
输入:
4
/
2 7
/ \ /
1 3 6 9
输出:
4
/
7 2
/ \ /
9 6 3 1
备注:
这个问题是受到 Max Howell 的 原问题 启发的 :
谷歌:我们90%的工程师使用您编写的软件(Homebrew),但是您却无法在面试时在白板上写出翻转二叉树这道题,这太糟糕了。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
// 解法一、 递归,后序遍历展平左右子树
// class Solution {
// public void flatten(TreeNode root) {
// if (root == null) { return ;}
// flatten(root.left);
// flatten(root.right);
// TreeNode right = root.right;
// root.right = root.left;
// root.left = null;
// TreeNode p = root;
// while (p.right != null) {
// p = p.right;
// }
// p.right = right;
// }
// }
// 解法二、 迭代实现,O(1)空间复杂度,最优解
class Solution {
public void flatten(TreeNode root) {
if (root == null) { return ;}
TreeNode cur = root;
// 一直往右看,只要节点有左孩子就左子树移到右子树
while (cur != null) {
if (cur.left != null) {
TreeNode right = cur.right;
// 下面和解法一一样,先记录右子树地址,左子树移到右子树,通过右子树找到保存的右子树的前驱节点,再将保存右子树接到前驱节点之后
cur.right = cur.left;
cur.left = null;
TreeNode p = cur;
while (p.right != null) {
p = p.right;
}
p.right = right;
}
cur = cur.right;
}
}
}
2792

被折叠的 条评论
为什么被折叠?



