0%

LeetCode 145. 二叉树的后序遍历

题目

LeetCode 145. 二叉树的后序遍历

思路

后序遍历是按照左-右-根的顺序.

按照根-左-右的顺序将节点入栈, 出栈顺序则是后序遍历的值.

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
LinkedList<Integer> list = new LinkedList<>();
if(root == null) {
return list;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
root = stack.pop();
list.addFirst(root.val);
if (root.left != null) {
stack.add(root.left);
}
if (root.right != null) {
stack.add(root.right);
}
}
return list;
}
}