145. Binary Tree Postorder Traversal

Given a binary tree, return the postorder traversal of its nodes' values.

 

Solution 1:
class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
      List<Integer> list = new ArrayList<>();
      if (root == null)
     return list;
      Stack<TreeNode> stack = new Stack<>();
      stack.push(root);
      while(!stack.empty()){
          root = stack.pop();
          list.add(0, root.val);
          if(root.left != null) 
              stack.push(root.left);
          if(root.right != null) 
              stack.push(root.right);
      }
      return list;
  }
}
 
Solution 2:
class Solution {
    List<Integer> result = new ArrayList<>();
    public List<Integer> postorderTraversal(TreeNode root) {     
        helper(root);                    
        return result;
    }
    
    private void helper(TreeNode root) {
         if (root == null)
            return;
         if (root.left != null)
             helper(root.left);
         if (root.right != null)
             helper(root.right);
         result.add(root.val);       
    }
}
posted @ 2019-03-15 13:33  MarkLeeBYR  阅读(97)  评论(0)    收藏  举报