首页 > 其他 > 详细

二叉树遍历 递归非递归

时间:2015-09-21 12:03:36      阅读:228      评论:0      收藏:0      [点我收藏+]

递归 

//递归先序遍历
    public static void pre(TreeNode root){
        if(root==null)  return;
        visit(root);
        if(root.left!=null) pre(root.left);
        if(root.right!=null) pre(root.right);
    }
    
     //递归中序遍历
    public static void in(TreeNode root) {
          if(root == null)return;
          if(root.left!=null)in(root.left);
          visit(root);
          if(root.right!= null)in(root.right);
         }
    
      //递归后序遍历
    public static void post(TreeNode root) {
          if(root == null)return;
          if(root.left!=null)in(root.left);
          if(root.right!= null)in(root.right);
          visit(root);
         }

非递归:

//非递归前序遍历--栈
    public static void preTraverse(TreeNode root){
        Stack<TreeNode> s=new Stack<TreeNode>();
        s.push(root);
        while(!s.isEmpty()){
            TreeNode current=s.pop();
            visit(current);
            if(current.right!=null) s.push(current.right);
            if(current.left!=null) s.push(current.left);
        }
        
    }
    //非递归前序遍历--队列
    public static void preTraverse2(TreeNode root){
        Queue<TreeNode> q=new LinkedList<TreeNode>();
        q.offer(root);
        while(!q.isEmpty()){
            TreeNode current=q.poll();
            visit(current);
            if(current.left!=null) q.offer(current.left);
            if(current.right!=null) q.offer(current.right);
            
        }
        
    }
    //非递归中序遍历
    public static void inTraverse(TreeNode root){
        Stack<TreeNode> s=new Stack<TreeNode>();
        TreeNode t=root;
        while(!s.isEmpty()||t!=null){
            if(t!=null){
                s.push(t);
                t=t.left;
            }else{
                t=s.pop();
                visit(t);
                t=t.right;            
                }
        }
        
    }

 

二叉树遍历 递归非递归

原文:http://www.cnblogs.com/hhhhh/p/4825513.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!