【Leetcode】145. Binary Tree Postorder Traversal 【递归&&非递归】

来源:互联网 发布:三体水滴视频 知乎 编辑:程序博客网 时间:2024/05/10 17:44

145. Binary Tree Postorder Traversal

  • Total Accepted: 108503
  • Total Submissions: 295063
  • Difficulty: Hard

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

For example:
Given binary tree {1,#,2,3},

   1    \     2    /   3

return [3,2,1].

Note: Recursive solution is trivial, could you do it iteratively?



递归代码:

public class Solution {    public List<Integer> postorderTraversal(TreeNode root) {        List<Integer> res = new ArrayList<Integer>();        if(root == null) return res;        preOrder(root,res);        return res;    }    private void preOrder(TreeNode root,List<Integer> res){        if(root == null) return;        preOrder(root.left,res);        preOrder(root.right,res);        res.add(root.val);    }}


0 0
原创粉丝点击