ID | Title | Difficulty | |
---|---|---|---|
Loading... |
145. Binary Tree Postorder Traversal
Easy
LeetCode
Stack, Tree, Depth-First Search, Binary Tree
Problem
Given the root of a binary tree, return the postorder traversal of its nodes’ values.
Example 1:
Input: root = [1,null,2,3]
Output: [3,2,1]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [1]
Output: [1]
Code
class Solution {
List<Integer> res;
public List<Integer> postorderTraversal(TreeNode root) {
res = new ArrayList<>();
if(root == null) return res;
helper(root);
return res;
}
private void helper(TreeNode root) {
if(root == null) return;
helper(root.left);
helper(root.right);
res.add(root.val);
}
}
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if(root == null) return res;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode cur = stack.pop();
res.add(0, cur.val);
if(cur.left != null) stack.push(cur.left);
if(cur.right != null) stack.push(cur.right);
}
return res;
}
}
按 <- 键看上一题!
144. Binary Tree Preorder Traversal
按 -> 键看下一题!
146. LRU Cache