题目描述

Given a binary tree, return the postorder traversal of its nodes’ values.
145. Binary Tree Postorder Traversal

方法思路

Approach1: recursive

class Solution {
    //Runtime: 0 ms, faster than 100.00%
    //Memory Usage: 36.2 MB, less than 25.53%
    List<Integer> res = new ArrayList<>();
    public List<Integer> postorderTraversal(TreeNode root) {
        if(root == null) return res;
        postorderTraversal(root.left);
        postorderTraversal(root.right);
        res.add(root.val);
        
        return res;
    }
} 

Approach2:iteratively

class Solution{
    //Runtime: 0 ms, faster than 100.00%
    //Memory Usage: 36.3 MB, less than 14.74% 
    public List<Integer> postorderTraversal(TreeNode root) {
        LinkedList<Integer> res = new LinkedList<>();
        if(root == null) return res;
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        
        while(!stack.isEmpty()){
            TreeNode node = stack.pop();
            res.addFirst(node.val);
            if(node.left != null)//判断左右子树是否为null,否则会有空指针异常
                stack.push(node.left);
            if(node.right != null)
                stack.push(node.right);
        }
        return res;
    }
}

相关文章:

  • 2021-09-10
  • 2021-07-16
  • 2021-11-26
  • 2021-09-28
  • 2021-12-16
  • 2022-03-02
  • 2022-01-16
猜你喜欢
  • 2021-12-28
  • 2021-10-14
相关资源
相似解决方案