思路:递归
// @Title: 二叉树的后序遍历 (Binary Tree Postorder Traversal)
// @Author: qisiii
// @Date: 2024-09-14 21:05:17
// @Runtime: 0 ms
// @Memory: 40.7 MB
// @comment: 递归
// @flag: GREEN
/**
* 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) {
List<Integer> result=new ArrayList<>();
sort(result,root);
return result;
}
private void sort(List<Integer> result,TreeNode node){
if(node!=null){
sort(result,node.left);
sort(result,node.right);
result.add(node.val);
}
}
}
+++ title = “二叉树的后序遍历 (Binary Tree Postorder Traversal)” draft = false +++
思路:迭代
// @Title: 二叉树的后序遍历 (Binary Tree Postorder Traversal)
// @Author: qisiii
// @Date: 2024-09-14 22:35:50
// @Runtime: 1 ms
// @Memory: 40.8 MB
// @comment: 迭代
// @flag: GREEN
/**
* 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) {
Stack<TreeNode> stack = new Stack<>();
List<Integer> result = new ArrayList<>();
HashSet<TreeNode> parent = new HashSet<>();
while (root != null || !stack.isEmpty()) {
if (root == null && parent.contains(stack.peek())) {
//当左子树和右子树都处理完了
result.add(stack.pop().val);
} else if (root == null) {
parent.add(stack.peek());
//然后处理右子树
root = stack.peek().right;
} else {
//先将左边的节点都放到队列
stack.push(root);
root = root.left;
}
}
return result;
}
}