本文實例為大家分享了java從上往下打印出二叉樹的具體代碼,供大家參考,具體內容如下
github:劍指offer編程全部試題
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
|
import java.util.arraylist; import java.util.stack; /** * * 劍指offer編程題(java實現)——第22題:從上往下打印出二叉樹 * * 題目描述 * 從上往下打印出二叉樹的每個節點,同層節點從左至右打印。 * */ public class test22 { arraylist<integer> arraylist = new arraylist<>(); // 每層依次入棧 stack<treenode> stack1 = new stack<>(); // 從stack1出棧的元素依次加入stack2,統一通過stack2找到他們的字節點并壓入stack1 stack<treenode> stack2 = new stack<>(); public arraylist<integer> printfromtoptobottom(treenode root) { if (root == null ) { return arraylist; // 空則返回 } stack1.push(root); while (!stack1.isempty()) { while (!stack1.isempty()) { treenode tmp = stack1.pop(); arraylist.add(tmp.val); stack2.push(tmp); } while (!stack2.isempty()) { treenode tmp2 = stack2.pop(); // 從左到右打印,所以右子樹先入棧 if (tmp2.right != null ) { stack1.push(tmp2.right); } if (tmp2.left != null ) { stack1.push(tmp2.left); } } } return arraylist; } public class treenode { int val = 0 ; treenode left = null ; treenode right = null ; public treenode( int val) { this .val = val; } } } //其他方法 /** public class solution { public arraylist<integer> printfromtoptobottom(treenode root) { arraylist<integer> list = new arraylist<integer>(); if(root == null) return list; deque<treenode> deque = new linkedlist<treenode>(); deque.add(root); while(!deque.isempty()){ treenode t = deque.pop(); list.add(t.val); if(t.left != null) deque.add(t.left); if(t.right != null) deque.add(t.right); } return list; } } */ |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/as1072966956/article/details/83040544