Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 92bc8e7

Browse files
committed
上下翻转二叉树
1 parent 60a7780 commit 92bc8e7

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,101 @@
11
package com.zhxh.codeproj.leetcode.vip200;
22

3+
import com.zhxh.codeproj.leetcode.__base.TreeNode;
4+
5+
import java.util.Stack;
6+
7+
/*
8+
156.上下翻转二叉树
9+
给定一个二叉树,其中所有的右节点要么是具有兄弟节点(拥有相同父节点的左节点)的叶节点,要么为空,将此二叉树上下翻转并将它变成一棵树, 原来的右节点将转换成左叶节点。返回新的根。
10+
例子:
11+
输入: [1,2,3,4,5]
12+
1
13+
/ \
14+
2 3
15+
/ \
16+
4 5
17+
18+
输出: 返回二叉树的根 [4,5,2,#,#,3,1]
19+
4
20+
/ \
21+
5 2
22+
/ \
23+
3 1
24+
说明:
25+
26+
对 [4,5,2,#,#,3,1] 感到困惑? 下面详细介绍请查看 二叉树是如何被序列化的。
27+
二叉树的序列化遵循层次遍历规则,当没有节点存在时,'#' 表示路径终止符。
28+
这里有一个例子:
29+
1
30+
/ \
31+
2 3
32+
/
33+
4
34+
\
35+
5
36+
上面的二叉树则被序列化为 [1,2,3,#,#,4,#,#,5].
37+
38+
*/
339
public class LeetCode156 {
440
public static void main(String[] args) {
41+
TreeNode.prettyPrintTree(new Solution().upsideDownBinaryTree(TreeNode.buildBinaryTree(new Integer[]{1, 2, 3, 4, 5})));
42+
TreeNode.prettyPrintTree(new Solution2().upsideDownBinaryTree(TreeNode.buildBinaryTree(new Integer[]{1, 2, 3, 4, 5})));
43+
}
44+
45+
/*
46+
递归,只要找到最左子树就行
47+
然后反转
48+
唯一要注意的一点是最后原本的根节点root的左右字数需要置null,否则会形成环
49+
*/
50+
static class Solution {
51+
public TreeNode upsideDownBinaryTree(TreeNode root) {
52+
if (root == null || root.left == null) return root;
53+
TreeNode ans = helper(root.left, root);
54+
//防止形成环
55+
root.left = null;
56+
root.right = null;
57+
return ans;
58+
}
59+
60+
public TreeNode helper(TreeNode left, TreeNode p) {
61+
TreeNode ans;
62+
if (left.left == null) {
63+
ans = left;
64+
} else {
65+
ans = helper(left.left, left);
66+
}
67+
left.left = p.right;
68+
left.right = p;
69+
return ans;
70+
}
71+
}
572

73+
/*
74+
迭代
75+
*/
76+
static class Solution2 {
77+
public TreeNode upsideDownBinaryTree(TreeNode root) {
78+
if (root == null) return null;
79+
Stack<TreeNode> stack = new Stack<>();
80+
TreeNode ans = null;
81+
TreeNode cur = root;
82+
//找最左子树
83+
while (cur != null) {
84+
stack.push(cur);
85+
cur = cur.left;
86+
}
87+
ans = stack.pop();
88+
cur = ans;
89+
//反转
90+
while (!stack.isEmpty()) {
91+
cur.right = stack.pop();
92+
cur.left = cur.right.right;
93+
cur = cur.right;
94+
}
95+
//防止形成环
96+
cur.left = null;
97+
cur.right = null;
98+
return ans;
99+
}
6100
}
7101
}

0 commit comments

Comments
 (0)