递归方法:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if(root==null){
return res;
}
postorder(root,res);
return res;
}
public void postorder(TreeNode root, List<Integer> res){
if(root==null)
return;
if(root.left!=null)
postorder(root.left,res);
if(root.right!=null)
postorder(root.right,res);
res.add(root.val);
}
}
非递归方法:
设置两个标记。只有当上一个访问的节点是右孩子时,才访问根节点。
/**
* 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<Integer>();
if (root == null) {
return res;
}
Stack<TreeNode> stack = new Stack<>();
TreeNode p = root;
TreeNode prev = null;
while (!stack.isEmpty() || p != null) {
while (p != null) {
stack.push(p);
p = p.left;
}
p = stack.peek();
// 已经访问过了
if (p.right == null || p.right == prev) {
stack.pop();
res.add(p.val);
prev = p;
p = null;
} else {
p = p.right;
}
}
return res;
}
}
第二种非递归遍历方法:
借助一个LinkedList,每次访问栈顶节点后采用头插法插入,从而保证左右根的访问顺序。
/**
* 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> res = new LinkedList<>();
if (root == null) {
return res;
}
TreeNode p = root;
stack.push(p);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
res.add(0, node.val);
if (node.left != null) {
stack.push(node.left);
}
if (node.right != null) {
stack.push(node.right);
}
}
return res;
}
}
网友评论