p226

LeetCode P226 Invert Binary Tree 题解

1.题目:

Invert a binary tree.

题意:

将一个二叉树反转

2.解题思路:

跟前面一题差不多啦~遍历的时候交换左右节点就好

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
 
package leetcode;

package leetcode;

import tool.TreeNode;

/**
*
* @author ZhangMengRou
*
*/
public class p226 {

public static void main(String[] args) {
// Scanner in = new Scanner(System.in);
// String a = in.nextLine();

//测试数据
TreeNode froot = null;
froot = new TreeNode(4);
TreeNode n2 = new TreeNode(2);
TreeNode n3 = new TreeNode(3);
TreeNode n9 = new TreeNode(9);
TreeNode n1 = new TreeNode(1);
TreeNode n6 = new TreeNode(6);
TreeNode n7 = new TreeNode(7);
froot.left = n2;
froot.right = n7;
n2.left = n1;
n2.right = n3;
n7.left = n6;
n7.right = n9;
TreeNode ans = invertTree(froot);
Check(ans);
// System.out.print(ans);
}

public static TreeNode invertTree(TreeNode root) {

TreeNode ans = root;
DFS(ans);

return ans;
}

public static void DFS(TreeNode t) {
// System.out.print("mmmm "+t.val+" "+count+"\n");
if (t == null || (t.left == null && t.right == null)) {
return;
}
TreeNode c = t.left;
t.left = t.right;
t.right = c;
if (!(t.left == null)) {

DFS(t.left);
}

if (!(t.right == null)) {

DFS(t.right);
}

return;
}

public static void Check(TreeNode t) {
System.out.print("mmmm " + t.val + " " + "\n");
if (t == null || (t.left == null && t.right == null)) {
return;
}
if (!(t.left == null)) {
System.out.print("L " + t.left.val + " " + "\n");

Check(t.left);
}

if (!(t.right == null)) {

System.out.print("R " + t.right.val + " " + "\n");
Check(t.right);
}

return;
}

}



//
//public class TreeNode {
//
// public int val;
// public TreeNode left;
// public TreeNode right;
// public TreeNode(int x) { val = x; }
//
//}



4.一些总结:

我会反转二叉树~听起来萌萌哒