二叉树非递归遍历

前提

 1 public class TreeNode {
 2     int val;
 3     TreeNode left;
 4     TreeNode right;
 5 
 6     TreeNode() {
 7     }
 8 
 9     TreeNode(int val) {
10         this.val = val;
11     }
12 
13     TreeNode(int val, TreeNode left, TreeNode right) {
14         this.val = val;
15         this.left = left;
16         this.right = right;
17     }
18 }
19 
20 // 构造二叉树
21 TreeNode node = new TreeNode(5);
22 node.right = new TreeNode(3);
23 TreeNode left = node.left = new TreeNode(1);
24 left.left = new TreeNode(2);
25 left.right = new TreeNode(4);

 

 

前序

 1     private static List<Integer> preorderTraversal(TreeNode head) {
 2         List<Integer> res = new ArrayList<>();
 3         if (head == null) {
 4             return res;
 5         }
 6         
 7         Stack<TreeNode> stack = new Stack<>();
 8         stack.push(head);
 9         while (!stack.isEmpty()) {
10             TreeNode top = stack.pop();
11             res.add(top.val);
12             if (top.right != null) {
13                 stack.push(top.right);
14             }
15             if (top.left != null) {
16                 stack.push(top.left);
17             }
18         }
19         System.out.println(res);
20         return res;
21     }

 

后序

private static List<Integer> postorderTraversal(TreeNode root) {

        List<Integer> res = new LinkedList<>();
        if (root == null) {
            return res;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode top = stack.pop();
            res.add(0, top.val);
            if (top.left != null) {
                stack.push(top.left);
            }
            if (top.right != null) {
                stack.push(top.right);
            }
        }
        System.out.println(res);
        return res;
    }

 

中序

private static List<Integer>  inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Stack<TreeNode> stack = new Stack<>();

        while (root != null || !stack.isEmpty()) {
            if (root != null) {
                stack.push(root);
                root = root.left;
                continue;
            }
            TreeNode top = stack.pop();
            res.add(top.val);
            root = top.right;
        }
        System.out.println(res);
        return res;
    }

 

 附录

递归代码

 1 public static List<Integer> res = new ArrayList<>();
 2 private static List<Integer> preorderTraversalRecur(TreeNode head) {
 3   if (head == null) {
 4     return res;
 5   }
 6   // 这里放其他位置,就是前序/中序/后序遍历  
 7   res.add(head.val);
 8   preorderTraversalRecur(head.left);
 9   preorderTraversalRecur(head.right);
10   return res;
11 }

 

 

posted @ 2021-03-06 16:36  程序员博博  阅读(74)  评论(0编辑  收藏  举报