二叉樹打印

題目:

有一棵二叉樹,請設計一個算法,按照層次打印這棵二叉樹。給定二叉樹的根結點root,請返回打印結果,結果按照每一層一個數組進行儲存,所有數組的順序按照層數從上往下,且每一層的數組內元素按照從左往右排列。保證結點數小於等於500。


解析:

1.初始化時,last=1,把1放入隊列;
2.將1出隊,把1的子孩子2,3放入隊列,更新nlast=3;
3.nlast更新完之後,打印上一次出隊的1,並和last比較,如果相同就打印換行,並更新last=nlast=3;
4.將2出隊,把2的子孩子4放入隊列,更新nlast=4;
5,nlast更新完以後,打印上一次出隊的2,並和last(3)比較,不相同,continue;
6.將3出隊,將3的子孩子5,6放入隊列,更新nlast=6;
7.nlast更新完以後,打印上一次出隊的3,並和last(3)比較, 相同就打印換行,並更新last=nlast=6;
…………
總結就是如下循環:(初始化last=根節點)
1.將A出隊,並將A的子孩子入隊,更新nlast=A最後入隊的子孩子;
2.打印上次出隊的傢伙A,並和last比較, 如果相同就打印換行,並更新last=nlast,如果 不相同,則continue

代碼:

import java.util.*;


/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
    public TreeNode(int val) {
        this.val = val;
    }
}*/
public class TreePrinter {
    public int[][] printTree(TreeNode root) {
        // write code here
        TreeNode last, nlast;
        Vector<Vector<Integer>> vec = new Vector<Vector<Integer>>();
        if (root == null){
            return null;
        }
        
        last = nlast = root;
        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        TreeNode node = null;
        Vector<Integer> v = new Vector<Integer>();
        while(!queue.isEmpty()){
            node = queue.poll();
            if(null != node.left){
                nlast = node.left;
                queue.add(node.left);
            }
            if(null != node.right){
                nlast = node.right;
                queue.add(node.right);
            }
            v.add(node.val);
            if(node == last){
                last = nlast;
                vec.addElement(v);
                v = new Vector<Integer>();
            }
        }
        
        int[][] result = new int[vec.size()][];
        int len;
        for(int i =0; i < vec.size(); i++){
            len = vec.get(i).size();
            result[i] = new int[len];
            for(int j = 0; j < len; j++)
                result[i][j] = vec.get(i).get(j);
        }
        
        return result;
        
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章