二叉树先序,中序和后序遍历

递归遍历

public void recur(TreeNode root) { // 打印时机
	if (root == null) return;
	//1 先序
	f(root.left);
	//2 中序
	f(root.right);
	//3 后序
}

递归序

alt

每个结点都被访问了三次 得到了下面递归序

ABDDDBEEEBACFFFCGGGCA

  1. 先序 第一次访问时打印 ABDECFG
  2. 中序 第二次访问时打印 DBEAFCG
  3. 后序 第三次访问时打印 DEBFGCA

非递归遍历 左神Ver.

public int[] preOrderTraversal(TreeNode root) {
        if(root == null)
            return new int[] {};
        ArrayList<Integer> array = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while(!stack.isEmpty()) {
            root = stack.pop();
            array.add(root.val);
            if(root.right != null)
                stack.push(root.right);
            if(root.left != null)
                stack.push(root.left);
        }
        return array.stream().mapToInt(Integer::intValue).toArray();
    }
    
    public int[] inOrderTraversal(TreeNode root) {
        if(root == null)
            return new int[] {};
        ArrayList<Integer> array = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        while(!stack.isEmpty() || root != null) {
            if(root != null) {
                stack.push(root);
                root = root.left;
            } else {
                TreeNode top = stack.pop();
                array.add(top.val);
                root = top.right;
            }
        }
        return array.stream().mapToInt(Integer::intValue).toArray();
    }
    
    public int[] postOrderTraversal(TreeNode root) {
        if(root == null)
            return new int[] {};
        ArrayList<Integer> array = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        Stack<Integer> help = new Stack<>();
        stack.push(root);
        while(!stack.isEmpty()) {
            root = stack.pop();
            help.push(root.val);
            if(root.left != null)
                stack.push(root.left);
            if(root.right != null)
                stack.push(root.right);
        }
        while(!help.isEmpty()) {
            array.add(help.pop());
        }
        return array.stream().mapToInt(Integer::intValue).toArray();
    }
posted @ 2022-02-10 23:04  brbrbr  阅读(79)  评论(0)    收藏  举报