0
点赞
收藏
分享

微信扫一扫

二叉树的后序遍历

卿卿如梦 2022-01-30 阅读 75
数据结构
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        if(root == null){
            return res;
        }
        TreeNode lastPopNode = null;

        while(!stack.isEmpty() || root != null){
            while(root != null){
                //当左右节点没有被记录时 才继续压栈
                if(lastPopNode == null || (root.right != lastPopNode && root.left != lastPopNode )){
                    stack.push(root);
                    if(root.right != null){
                        stack.push(root.right);
                    }
                    root = root.left;
                }else{
                    res.add(root.val);
                    lastPopNode = root;
                    break;
                }
            }
            if(stack.isEmpty()){
                break;
            }
            root = stack.pop();
            //左右节点均为空时,记录结果
            if(root.left == null && root.right == null){
                res.add(root.val);
                //用于判断左右节点是否被访问过
                lastPopNode = root;
                if(stack.isEmpty()){
                    break;
                }else{
                    root = stack.pop();
                }
            }
        }
        return res;
    }
}
举报

相关推荐

0 条评论