题解 | #二叉树的后序遍历#

二叉树的后序遍历

https://www.nowcoder.com/practice/1291064f4d5d4bdeaefbf0dd47d78541

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * @param root TreeNode类
     * @return int整型一维数组
     */
    public int[] postorderTraversal (TreeNode root) {
        LinkedList<TreeNode> stack = new LinkedList<>();
        ArrayList<Integer> list = new ArrayList<>();
        TreeNode curr = root;
        TreeNode pop = null;
        while (curr != null || !stack.isEmpty()) {
            if (curr != null) {
                stack.push(curr);
                curr = curr.left;
            } else {
                TreeNode peek = stack.peek();
                if(peek.right == null || peek.right == pop){
                    pop = stack.pop();
                    list.add(pop.val);
                }else{
                    curr = peek.right;
                }
            }
        }
        return list.stream().mapToInt(Integer::intValue).toArray();
    }
}

全部评论

相关推荐

10-14 10:56
已编辑
长沙学院 嵌入式软件开发
痴心的00后拿到了ssp:hr面挂了,无所谓了反正不去😃
点赞 评论 收藏
分享
赏个offer求你了:友塔HR还专门加我告诉我初筛不通过😂
点赞 评论 收藏
分享
评论
1
收藏
分享
牛客网
牛客企业服务