Skip to content

Commit 8535fa4

Browse files
committed
ok
1 parent 17abfef commit 8535fa4

File tree

1 file changed

+48
-3
lines changed

1 file changed

+48
-3
lines changed

src/com/leetcode/scanBinaryTree.java

Lines changed: 48 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
//二叉树的遍历
22
package com.leetcode;
3-
import java.util.ArrayList;
4-
import java.util.LinkedList;
5-
import java.util.Stack;
3+
import java.util.*;
64

75
public class scanBinaryTree {
86
private static class TreeNode {
@@ -113,6 +111,51 @@ public static ArrayList<Integer> cengci(TreeNode root) {
113111
}
114112
return list;
115113
}
114+
public static List<Integer> zuoShiTu(TreeNode root) { //左视图
115+
if (root == null) {
116+
return new ArrayList<>();
117+
}
118+
List<Integer> res = new ArrayList<>();
119+
LinkedList<TreeNode> queue = new LinkedList<>();
120+
queue.offer(root);
121+
while (!queue.isEmpty()) {
122+
int size = queue.size();
123+
int curLevelSize = size;
124+
while (size > 0) {
125+
TreeNode node = queue.poll();
126+
if (size == curLevelSize) {
127+
res.add(node.val);
128+
}
129+
if (node.left != null)
130+
queue.offer(node.left);
131+
if (node.right != null)
132+
queue.offer(node.right);
133+
size -= 1;
134+
}
135+
}
136+
return res;
137+
}
138+
public static List<Integer> youShiTu(TreeNode root) { //右视图
139+
if (root == null)
140+
return new ArrayList<>();
141+
Queue<TreeNode> queue = new LinkedList<>();
142+
List<Integer> res = new ArrayList<>();
143+
queue.offer(root);
144+
while (!queue.isEmpty()) {
145+
int size = queue.size();
146+
while (size > 0) {
147+
TreeNode node = queue.poll();
148+
if (node.left != null)
149+
queue.offer(node.left);
150+
if (node.right != null)
151+
queue.offer(node.right);
152+
size -= 1;
153+
if (size == 0)
154+
res.add(node.val);
155+
}
156+
}
157+
return res;
158+
}
116159

117160
public static void main(String[] args) {
118161
TreeNode root = new TreeNode(1);
@@ -144,5 +187,7 @@ public static void main(String[] args) {
144187
post.postOrder(root);
145188
System.out.println("后序遍历非递归:" + post.list);
146189
System.out.println("层次遍历:" + cengci(root));
190+
System.out.println("左视图:" + zuoShiTu(root));
191+
System.out.println("右视图:" + youShiTu(root));
147192
}
148193
}

0 commit comments

Comments
 (0)