采用非递归的方法进行二叉树的后序遍历
思路:用栈作为辅助空间,先从根往左一直入栈,直到为空,然后判断栈顶元素的的右孩子,如果不为空且未被访问过,则从它开始重复左孩子入栈的过程,否则说明此时栈顶为要访问的节点(因为左右孩子都是要么为空要么已经被访问过了),出栈后访问即可,接下来再判断栈顶元素的右孩子,直到栈空。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public ArrayList<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> list= new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
//p记录当前节点,pre记录上一次访问的节点
TreeNode p = root, pre = null;
while (p != null || !stack.isEmpty()) {
//左孩子一直入栈,直到左孩子为空
if (p != null) {
stack.push(p);
p = p.left;
}
else {
p = stack.peek();
p = p.right;
//如果栈顶元素的右孩子不为空,且未被访问过,则右孩子进栈,
//然后重复左孩子一直进栈直到为空的情况
if (p != null && p != pre) {
stack.push(p);
p = p.left;
}
else {
//否则出栈,访问。pre记录刚刚访问的节点
p = stack.pop();
list.add(p.val);
pre = p;
p = null;
}
}
}
return list;
}
}
递归遍历
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
ArrayList<Integer> list= new ArrayList<Integer>();
public ArrayList<Integer> postorderTraversal(TreeNode root) {
if (root == null) {
return list;
}
if (root.left != null) {
postorderTraversal(root.left);
}
if (root.right != null) {
postorderTraversal(root.right);
}
list.add(root.val);
return list;
}
}