01 August 2014

二叉树的非递归遍历及leetcode终结

Leetcode刷完了,许多没记,总体面试中遇到太难的算法题。另外Leetcode中的题目一定要用最优的代码最简洁的代码,不然就是白刷。

##前序 public class Solution { public List preorderTraversal(TreeNode root) { List l = new ArrayList(); TreeNode p = root; TreeNode []stack = new TreeNode[1000]; int top =0; if(root!=null) stack[top++]=root; while(top>0) { l.add(p.val); //先放右边 再放左边 if(p.right!=null) stack[top++]=p.right; if(p.left!=null) stack[top++]=p.left; p=stack[--top]; } return l; } }

##中序

public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> re = new ArrayList<Integer>();
        TreeNode stack[]=new TreeNode[1000];
        int top=0;
        TreeNode p = root;
        while(top>0|| p!=null)  
        {  
            if(p!=null)  
            {  
                stack[top++]=p;
                p= p.left;  
            }else{  
                p = stack[--top];  
                re.add(p.val);  
                p = p.right;  
            }  
        }  
        return re;
    }
}

##后序

public class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
       List<Integer> l = new ArrayList<Integer>();
        TreeNode p = root;
        TreeNode []stack = new TreeNode[1000];
        int tail=0;
        int top =0;
        if(root!=null)
            stack[top++]=root;
        while(top>0)
        {
            /* 后序遍历可以看成右边再左边的前序遍历的结果的逆序。 */
            l.add(0,p.val);
            if(p.left!=null)
                stack[top++]=p.left;
            if(p.right!=null)
                 stack[top++]=p.right;
            p=stack[--top];
        }
        return l;
    }
}


blog comments powered by Disqus