其他分享
首页 > 其他分享> > 二叉树前中后序遍历(循环实现)

二叉树前中后序遍历(循环实现)

作者:互联网

前序遍历

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

中序遍历

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

        return res;
    }
}

后序遍历

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

        return res;
    }
}

标签:遍历,前中,res,List,二叉树,new,null,root,stack
来源: https://blog.csdn.net/oh_lala/article/details/122805426