二叉树的遍历算法

1、先序遍历

class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        if(root == null) return new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        List<Integer> list = new ArrayList<>();
        stack.push(root); //把头节点入栈
        while(!stack.isEmpty()){
            TreeNode cur = stack.pop();//1、每次从栈中弹出一个节点
            list.add(cur.val);//2、处理cur
            if(cur.right != null){//3、如果有右节点,入栈
                stack.push(cur.right);
            }
            if(cur.left != null){
                stack.push(cur.left);//4、如果有左节点,入栈
            }
        }
        return list;
    }
}

2、中序遍历

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        if(root == null) return new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        List<Integer> list = new ArrayList<>();
        while(!stack.isEmpty() || root != null){
            if(root != null){
                stack.push(root);
                root = root.left;
            }else{
                root = stack.pop();
                list.add(root.val);
                root = root.right;
            }
        }
        return list;
    }
}

3、后序遍历

class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        if(root == null) return new ArrayList<>();
        //可以在前序版本上修改,添加一个辅助栈
        Stack<TreeNode> stack = new Stack<>();
        Stack<Integer> assist = new Stack<>();
        List<Integer> list = new ArrayList<>();
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode cur = stack.pop();//每次从栈中弹出一个节点
            assist.push(cur.val);//2、处理cur,把其值压入辅助栈
            if(cur.left != null){
                stack.push(cur.left);//3、如果有左节点,入栈
            }
            if(cur.right != null){//4、如果有右节点,入栈
                stack.push(cur.right);
            }
        }
        //读出辅助栈内容
        while(!assist.isEmpty()){
            list.add(assist.pop());
        }
        return list;
    }
}
posted @ 2022-03-07 16:57  nofight  阅读(43)  评论(0)    收藏  举报