二叉树—前序遍历、中序遍历(非递归)

朱雀 2021-09-18 05:06 504阅读 0赞

【转载】https://www.cnblogs.com/bigsai/p/11393609.html
层级遍历

  1. public void cengxu(node t) {//层序遍历
  2. Queue<node> q1 = new ArrayDeque<node>();
  3. if (t == null)
  4. return;
  5. if (t != null) {
  6. q1.add(t);
  7. }
  8. while (!q1.isEmpty()) {
  9. node t1 = q1.poll();
  10. if (t1.left != null)
  11. q1.add(t1.left);
  12. if (t1.right != null)
  13. q1.add(t1.right);
  14. System.out.print(t1.value + " ");
  15. }
  16. System.out.println();
  17. }

非递归前序

  1. public void qianxu3(node t)// 非递归前序 栈 先左后右 t一般为root
  2. {
  3. Stack<node> q1 = new Stack<node>();
  4. if (t == null)
  5. return;
  6. if (t != null) {
  7. q1.push(t);
  8. }
  9. while (!q1.empty()) {
  10. node t1 = q1.pop();
  11. if (t1.right != null) {
  12. q1.push(t1.right);
  13. }
  14. if (t1.left != null) {
  15. q1.push(t1.left);
  16. }
  17. System.out.print(t1.value + " ");
  18. }
  19. }
  20. public void qianxu2(node t) {
  21. Stack<node> q1 = new Stack();
  22. while(!q1.isEmpty()||t!=null)
  23. {
  24. if (t!=null) {
  25. System.out.print(t.value+" ");
  26. q1.push(t);
  27. t=t.left;
  28. }
  29. else {
  30. t=q1.pop();
  31. t=t.right;
  32. }
  33. }
  34. }

中序遍历

  1. public void zhongxu2(node t) {
  2. Stack<node> q1 = new Stack();
  3. while(!q1.isEmpty()||t!=null)
  4. {
  5. if (t!=null) {
  6. q1.push(t);
  7. t=t.left;
  8. }
  9. else {
  10. t=q1.pop();
  11. System.out.print(t.value+" ");
  12. t=t.right;
  13. }
  14. }
  15. }

发表评论

表情:
评论列表 (有 0 条评论,504人围观)

还没有评论,来说两句吧...

相关阅读