0%

二叉树常见操作

遍历等等

Java:

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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
public class TreeNode {
int val;
TreeNode left;
TreeNode right;

TreeNode(int x) {
val = x;
}

@Override
public String toString() {
return "" + val;
}
}

//非递归的前序遍历
public List<TreeNode> getPreOrderIteratively(TreeNode p) {
return getPreOrderIteratively(p, true);
}

//对于非叶子节点,如果有一个子树位空会把它打印出来
private List<TreeNode> getPreOrderIteratively(TreeNode p, boolean printNull) {
Stack<TreeNode> stack = new Stack<>();
List<TreeNode> listP = new ArrayList<>();
while (p != null || !stack.isEmpty()) {
while (p != null) {
listP.add(p);
stack.push(p);
if (printNull && !isLeaf(p) && p.left == null) {
listP.add(null);
}
p = p.left;
}
if (!stack.isEmpty()) {
p = stack.pop();
if (printNull && !isLeaf(p) && p.right == null) {
listP.add(null);
}
p = p.right;
}
}
return listP;
}

private boolean isLeaf(TreeNode parent) {
if (parent.left == null && parent.right == null) {
return true;
}
return false;
}

private boolean isSameTreeNode(TreeNode p1, TreeNode p2) {
if (p1 == null && p2 == null) {
return true;
}
if (p1 == null || p2 == null) {
return false;
}
return p1.val == p2.val;
}


//递归的层次遍历
public List<List<Integer>> levelOrderRecursively (TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
result = levelOrderInternal(root, result,0);
return result;
}

private List<List<Integer>> levelOrderInternal(TreeNode node, List<List<Integer>> result, int level){
if(node == null) return result;
if(result.size() <= level){
result.add(new ArrayList<>());
}
result.get(level).add(node.val);
levelOrderInternal(node.left,result, level+1);
levelOrderInternal(node.right,result,level+1);
return result;
}

//非递归的层次遍历
public List<List<Integer>> levelOrderIteratively(TreeNode root) {
List<List<Integer>> ret = new ArrayList<>();
if(root ==null){
return ret;
}

Queue<TreeNode> queue = new LinkedList<>();
List<Integer> list = new ArrayList<>();

TreeNode levelStart = root ;
queue.offer(root);

while(!queue.isEmpty()){
TreeNode node = queue.poll();
if(node == levelStart){
list = new ArrayList<>();
ret.add(list);
levelStart = null ;
}
list.add(node.val);

if(node.left !=null){
queue.offer(node.left);
if(levelStart == null){
levelStart = node.left;
}
}
if(node.right !=null){
queue.offer(node.right);
if(levelStart == null){
levelStart = node.right ;
}
}
}
return ret ;
}