L52— 144. 二叉树的后序遍历(深搜)—Java版

作者 : admin 本文共1044个字,预计阅读时间需要3分钟 发布时间: 2024-06-16 共1人阅读

1.题目描述

L52— 144. 二叉树的后序遍历(深搜)—Java版插图

2.思路

(1)二叉树后序遍历:左右根
(2)根节点的压入:

根节点首先被压入stack中,然后被弹出并压入output中。
遍历过程:

stack用于存储需要遍历的节点。
output用于反转遍历顺序。
入栈顺序:

左子节点先入栈,右子节点后入栈。这样出栈顺序是右-左。
构建结果:

将output中的节点依次弹出并存入结果列表result中,这样得到的顺序就是后序遍历(左-右-根)。

3.代码实现

/**
 * 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> result=new ArrayList<>();
        if(root==null)
        {
            return result;
        }
        Stack<TreeNode> stack=new Stack<>();//初始化一个空栈
        stack.push(root);//将根节点的内容压入栈中,比如root = [1,null,2,3]
        //辅助栈,用户反转遍历顺序。反转是根右左,正确的是左右根。
        Stack<TreeNode> output=new Stack<>();

        while(!stack.isEmpty())//当栈不空的时候
        {
            TreeNode current=stack.pop();//将栈中当前值弹出
            output.push(current);//将当前节点推入栈
            //入栈先左后右,出栈先右后左
              if(current.left!=null) //根右左
            {
                stack.push(current.left);

            }
            
            if(current.right!=null)
            {
                stack.push(current.right);
            }
        }
        while(!output.isEmpty())
        {
            result.add(output.pop().val);//弹出的顺序正好是左右根
        }

       return result;
    }
}
本站无任何商业行为
个人在线分享-虚灵IT资料分享 » L52— 144. 二叉树的后序遍历(深搜)—Java版
E-->