java编程题之从上往下打印出二叉树

2025-05-29 0 106

本文实例为大家分享了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;

}

}

*/

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。

原文链接:https://blog.csdn.net/as1072966956/article/details/83040544

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 java编程题之从上往下打印出二叉树 https://www.kuaiidc.com/109851.html

相关文章

发表评论
暂无评论