[Leetcode学习-java]Print Binary Tree(打印二叉树)

问题:

难度:medium

说明:

给出一个二叉树,然后将二叉树打印为二维数组形式。

问题链接:https://leetcode.com/problems/print-binary-tree/

输入范围:

树的高度为10以内。

输入案例:

案例1:
Input:
     1
    /
   2
Output:
[["", "1", ""],
 ["2", "", ""]]

案例2:
Input:
     1
    / \
   2   3
    \
     4
Output:
[["", "", "", "1", "", "", ""],
 ["", "2", "", "", "", "3", ""],
 ["", "", "4", "", "", "", ""]]

案例3:
Input:
      1
     / \
    2   5
   / 
  3 
 / 
4 
Output:

[["",  "",  "", "",  "", "", "", "1", "",  "",  "",  "",  "", "", ""]
 ["",  "",  "", "2", "", "", "", "",  "",  "",  "",  "5", "", "", ""]
 ["",  "3", "", "",  "", "", "", "",  "",  "",  "",  "",  "", "", ""]
 ["4", "",  "", "",  "", "", "", "",  "",  "",  "",  "",  "", "", ""]]

我的代码:

先观察规律,N为行数,i 为第 i 行,每一行都有 2 ^ N - 1个字符,元素左右两边都是 2^(N - i - 1) - 1 的空格数量,而每一行每两个元素之间都有 2^(N - i) - 1个空格。然后进行BFS算法处理,所以得出:

class Solution {
    // 因为最多10行,所以弄 2 ^ 9长度的栈刚好进行BFS
    private static TreeNode[] stack = new TreeNode[(int)Math.pow(2,9)];
    private static TreeNode[] stack2 = new TreeNode[(int)Math.pow(2,9)];
    private static int top = 0;
    private static int top2 = 0;
    // 注意这里弄成静态的空字符串,如果用list.add(""),会慢很多,明显空字符串还得创建
    private static String BLANK = "";
    
    public List<List<String>> printTree(TreeNode root) {
        top = 0;
        if(root != null) stack[top ++] = root;
        List<List<String>> res = new ArrayList<List<String>>();
        
        // 把所有的 value 压倒结果集
        while(top != 0) {
            top2 = 0;
            int index = 0;
            boolean isNull = true;
            List<String> list = new ArrayList<String>();
            while(index < top) {
                TreeNode node = stack[index ++];
                if(node == null) {
                    list.add(BLANK);
                    stack2[top2 ++] = null;
                    stack2[top2 ++] = null;
                } else {
                    list.add(String.valueOf(node.val));
                    stack2[top2 ++] = node.left;
                    stack2[top2 ++] = node.right;
                    isNull = false;
                }
            }
            if(isNull) break;
            res.add(list);
            // 交换双栈数据
            top = top2;
            TreeNode[] stack3 = stack;
            stack = stack2;
            stack2 = stack3;
        }
        
        // 将空格补齐
        int lev = res.size();
        int space = (int)Math.pow(2,lev) - 1;
        for(int i = lev;i -- > 0;) {
            List<String> list = res.get(i);
            for(int j = list.size() - 1;j -- > 0;)
                for(int x = (int)Math.pow(2,lev - i) - 1;x -- > 0;) 
                    list.add(j + 1, BLANK);
            for(int x = (int)Math.pow(2,lev - i - 1) - 1;x -- > 0;) {
                list.add(0,BLANK);
                list.add(BLANK);
            }
        }
        
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_28033719/article/details/107173688