p145

LeetCode p145 Binary Tree Postorder Traversal 题解

1.题目:

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].

题意:

返回一个数的后序遍历。

2.解题思路:

后序遍历首先遍历左子树,然后遍历右子树,最后访问根结点。
dp

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> ans = new ArrayList<Integer>();
public List<Integer> postorderTraversal(TreeNode root) {
if (root == null)
return ans;
if (root.left != null)
postorderTraversal(root.left);
if (root.right != null)
postorderTraversal(root.right);
ans.add(root.val);
return ans;
}
}


4.一些总结: