刷题顺序按照代码随想录建议
题目描述
英文版描述
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]
Constraints:
- The number of the nodes in the tree is in the range
[0, 100]
. -100 <= Node.val <= 100
英文版地址
中文版描述
给你一棵二叉树的根节点 root
,返回其节点值的 后序遍历 。
示例 1:
输入: root = [1,null,2,3] 输出: [3,2,1]
示例 2:
输入: root = [] 输出: []
示例 3:
输入: root = [1] 输出: [1]
提示:
- 树中节点的数目在范围
[0, 100]
内 -100 <= Node.val <= 100
中文版地址
解题方法
递归法
java
/**
* 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 {
List<Integer> result = new LinkedList<>();
public List<Integer> postorderTraversal(TreeNode root) {
traversal(root);
return result;
}
private void traversal(TreeNode root) {
if (root == null) {
return;
}
traversal(root.left);
traversal(root.right);
result.add(root.val);
}
}
复杂度分析
- 时间复杂度:O(n),其中 n 是二叉树的节点数。每一个节点恰好被遍历一次
- 空间复杂度:O(n),为递归过程中栈的开销,平均情况下为 O(logn),最坏情况下树呈现链状,为 O(n)
迭代法
java
/**
* 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 {
List<Integer> result = new ArrayList<>();
public List<Integer> postorderTraversal(TreeNode root) {
if (root == null) {
return result;
}
ArrayDeque<TreeNode> deque = new ArrayDeque<>();
deque.add(root);
while (!deque.isEmpty()) {
TreeNode treeNode = deque.pollLast();
if (treeNode != null) {
result.add(treeNode.val);
TreeNode left = treeNode.left;
if (left != null) {
deque.addLast(left);
}
TreeNode right = treeNode.right;
if (right != null) {
deque.addLast(right);
}
}
}
List<Integer> result2 = new LinkedList<>();
for (int i = result.size() - 1; i >= 0; i--) {
result2.add(result.get(i));
}
return result2;
}
}
复杂度分析
- 时间复杂度:O(n),其中 n 是二叉树的节点数。每一个节点恰好被遍历一次
- 空间复杂度:O(n),为迭代过程中栈的开销,平均情况下为 O(logn),最坏情况下树呈现链状,为 O(n)