地址:https://oj.leetcode.com/problems/binary-tree-postorder-traversal/
题意就是完成二叉树的后序遍历,我们知道如果使用递归进行二叉树后序遍历将是非常简单的事情。
public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer > ans = new ArrayList<>();
Traversal(root, ans);
return ans;
}
public void Traversal(TreeNode root,List<Integer > ans){
if(root!=null){
Traversal(root.left, ans);
Traversal(root.right, ans);
ans.add(root.val);
}
}
}
但是这里需要进行非递归的后序遍历,在这篇博文中已经写过中序遍历的非递归程序和一些经典二叉搜索树的面试题:http://blog.csdn.net/huruzun/article/details/21799441 用C++去实现的。
非递归后序遍历的算法思想:要保证根结点在左孩子和右孩子访问之后才能访问,因此对于任一结点P,先将其入栈。如果P不存在左孩子和右孩子,则可以直接访问它;或者P存在左孩子或者右孩子,但是其左孩子和右孩子都已被访问过了,则同样可以直接访问该结点。若非上述两种情况,则将P的右孩子和左孩子依次入栈,这样就保证了每次取栈顶元素的时候,左孩子在右孩子前面被访问,左孩子和右孩子都在根结点前面被访问。
public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer > ans = new ArrayList<>();
if(root == null){
return ans;
}
Stack<TreeNode> st = new Stack<>();
st.push(root);
TreeNode pre = null;
TreeNode cur;
while(st.size()!=0){
cur = st.peek();
if((cur.left==null&&cur.right==null)||(pre!=null && ((pre==cur.left)||(pre==cur.right)))){
ans.add(cur.val);
st.pop();
pre = cur;
}else {
if(cur.right!=null){
st.add(cur.right);
}
if(cur.left!=null){
st.add(cur.left);
}
}
}
return ans;
}
}
最后把所有测试代码也贴出来
package 二叉搜索树遍历;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer > ans = new ArrayList<>();
Traversal(root, ans);
return ans;
}
public void Traversal(TreeNode root,List<Integer > ans){
if(root!=null){
Traversal(root.left, ans);
Traversal(root.right, ans);
ans.add(root.val);
}
}
public List<Integer> postorderTraversal2(TreeNode root) {
List<Integer > ans = new ArrayList<>();
if(root == null){
return ans;
}
Stack<TreeNode> st = new Stack<>();
st.push(root);
TreeNode pre = null;
TreeNode cur;
while(st.size()!=0){
cur = st.peek();
if((cur.left==null&&cur.right==null)||(pre!=null && ((pre==cur.left)||(pre==cur.right)))){
ans.add(cur.val);
st.pop();
pre = cur;
}else {
if(cur.right!=null){
st.add(cur.right);
}
if(cur.left!=null){
st.add(cur.left);
}
}
}
return ans;
}
// 这里root 是传值,所以必须返回root值使得树能建立。
public TreeNode insert(TreeNode root,int val){
if(root == null){
root = new TreeNode(val);
root.left = null;
root.right = null;
return root;
}
else {
if(root.val<val){
root.right = insert(root.right, val);
}else if(root.val>val){
root.left = insert(root.left, val);
}else {
}
}
return root;
}
public static void main(String[] args) {
int []num = {1,2};
TreeNode root = null;
Solution s = new Solution();
for(int i=0;i<num.length;i++){
root = s.insert(root, num[i]);
}
System.out.println(s.postorderTraversal(root));
System.out.println(s.postorderTraversal2(root));
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}