二叉树的后续遍历
给你一棵二叉树的根节点 root
,返回其节点值的 后序遍历 。
示例 1:
输入:root = [1,null,2,3]
输出:[3,2,1]
递归版本实现
/**
* 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> res = new ArrayList<>();
postorder(root,res);
return res;
}
public void postorder (TreeNode root,List res) {
if(root == null) {
return;
}
postorder(root.left,res);
postorder(root.right,res);
res.add(root.val);
}
}
迭代版本实现
整体思路:
- 首先创建两个栈,s1和s2,将头节点放入s1中
- s1出栈,将出栈节点的左节点和右节点分别入栈s1,并将出栈节点放入s2中
- 重复第二步,直到s1栈为空
- 将s2所有节点出栈,放入res中返回
代码实现
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> s1 = new Stack<>();
Stack<TreeNode> s2 = new Stack<>();
if(root !=null) {
s1.push(root);
}
while(!s1.isEmpty()){
TreeNode node = s1.pop();
if(node.left != null) {
s1.push(node.left);
}
if(node.right != null) {
s1.push(node.right);
}
s2.push(node);
}
while(!s2.isEmpty()) {
TreeNode node = s2.pop();
res.add(node.val);
}
return res;
}
}