给你一棵二叉树的根节点 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);
}
}
整体思路:
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;
}
}