题解 | #按之字形顺序打印二叉树#

按之字形顺序打印二叉树

http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0

两个队列交替使用,比较好想,但是效率有点底。

import java.util.ArrayList;

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
import java.util.*;
public class Solution {
    public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
        Queue<TreeNode> lqueue = new LinkedList<>();
        Queue<TreeNode> rqueue = new LinkedList<>();
        TreeNode p1,p2;
        ArrayList<ArrayList<Integer> > re = new ArrayList<>();
        ArrayList<Integer> list = new ArrayList<>();
        lqueue.offer(pRoot);
        if(pRoot == null){
            return re;
        }
        while(!lqueue.isEmpty() || !rqueue.isEmpty()){
            while(!lqueue.isEmpty()){
                p1 = lqueue.poll();
                list.add(p1.val);
                if(p1.left != null ){
                    rqueue.offer(p1.left);
                }
                if(p1.right != null ){
                    rqueue.offer(p1.right);
                }
            }
            if(list.size() != 0){
            re.add(new ArrayList(list));
            }
            list.clear();
            while(!rqueue.isEmpty()){
                p1 = rqueue.poll();
                list.add(0,p1.val);
                if(p1.left != null ){
                    lqueue.offer(p1.left);
                }
                if(p1.right != null ){
                    lqueue.offer(p1.right);
                }
            }
            if(list.size() != 0){
            re.add(new ArrayList(list));
            }
            list.clear();
        }
        
        return re;
        
        
    }

}
全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务