leetcode 655. Print Binary Tree

257 篇文章 17 订阅

Print a binary tree in an m*n 2D string array following these rules:

  1. The row number m should be equal to the height of the given binary tree.
  2. The column number n should always be an odd number.
  3. The root node's value (in string format) should be put in the exactly middle of the first row it can be put. The column and the row where the root node belongs will separate the rest space into two parts (left-bottom part and right-bottom part). You should print the left subtree in the left-bottom part and print the right subtree in the right-bottom part. The left-bottom part and the right-bottom part should have the same size. Even if one subtree is none while the other is not, you don't need to print anything for the none subtree but still need to leave the space as large as that for the other subtree. However, if two subtrees are none, then you don't need to leave space for both of them.
  4. Each unused space should contain an empty string "".
  5. Print the subtrees following the same rules.

Example 1:

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

Example 2:

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

Example 3:

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

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

Note: The height of binary tree is in the range of [1, 10].

这个也是简单题。

我们可以看到,结果 List<List<String>> 的size是 树的高度。那么结果 List<List<String>> 中每一行 list 的 size 是多少呢?

  • row = 1 => col = 1 = 2^1 - 1
  • row = 2 => col = 3 = 2^2 - 1
  • row = 3 => col = 7 = 2^3 - 1
  • row = 4 => col = 15 = 2^4 - 1
    ...
  • row = m => col = 2^m - 1

可以被归纳为 2^height - 1 。

然后我们可以 level by level 来填入node值。

public List<List<String>> printTree(TreeNode root) {
	int height=getHeight(root);
	int size=(int)Math.pow(2, height)-1;
	List<List<String>> result=new ArrayList<List<String>>();
	for(int i=0;i<height;i++){
		List<String> list=new ArrayList<String>();
		for(int j=0;j<size;j++){
			list.add("");
		}
		result.add(list);
	}
	helper(result, root, 0, 0, size-1);
	return result;
}

public void helper(List<List<String>> result,TreeNode node,
		int level,int left,int right){
	if(node==null){
		return;
	}
	int index=(left+right)/2;
	result.get(level).set(index, node.val+"");
	helper(result, node.left, level+1, left, index-1);
	helper(result, node.right, level+1, index+1, right);
}

public int getHeight(TreeNode node){
	if(node==null){
		return 0;
	}
	return Math.max(1+getHeight(node.left), 1+getHeight(node.right));
}
大神的解法都跟我一样的,英雄所见略同啊哈哈。
这道题有solutions: https://leetcode.com/problems/print-binary-tree/solution/

Solution


Approach #1 Recursive Solution[Accepted]

We start by initializing a resres array with the dimensions being heightheigh2^{height}-12height1. Here, heightheight refers to the number of levels in the given tree. Initially, we fill the complete array with "" . After this we make use of a recursive function fill(res, root, i, l, r) which fills the resres array such that the current element has to be filled in i^{th}ith row,  ll and rr refer to the left and the right boundaries of the columns in which the current element can be filled.

In every recursive call, we do as follows:

  1. If we've reached the end of the tree, i.e. if root==null, return.

  2. Determine the column in which the current element(rootroot) needs to be filled, which is the middle of ll and rr .

  3. Make the recursive call for the left child of the rootroot using fill(res, root.left, i + 1, l, (l + r) / 2).

  4. Make the recursive call for the right child of the rootroot using fill(res, root.right, i + 1, (l + r + 1) / 2, r).

Java

public class Solution {
    public List<List<String>> printTree(TreeNode root) {
        int height = getHeight(root);
        String[][] res = new String[height][(1 << height) - 1];
        for(String[] arr:res)
            Arrays.fill(arr,"");
        List<List<String>> ans = new ArrayList<>();
        fill(res, root, 0, 0, res[0].length);
        for(String[] arr:res)
            ans.add(Arrays.asList(arr));
        return ans;
    }
    public void fill(String[][] res, TreeNode root, int i, int l, int r) {
        if (root == null)
            return;
        res[i][(l + r) / 2] = "" + root.val;
        fill(res, root.left, i + 1, l, (l + r) / 2);
        fill(res, root.right, i + 1, (l + r + 1) / 2, r);
    }
    public int getHeight(TreeNode root) {
        if (root == null)
            return 0;
        return 1 + Math.max(getHeight(root.left), getHeight(root.right));
    }
}

Complexity Analysis

  • Time complexity : O(h*2^h)O(h2h). We need to fill the resres array of size hhx2^h - 12h1. Here, hh refers to the height of the given tree.

  • Space complexity : O(h*2^h)O(h2h)resres array of size hhx2^h - 12h1 is used.


Approach #2 Using queue(BFS)[Accepted]

Java

public class Solution
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    class Params {
        Params(TreeNode n, int ii, int ll, int rr) {
            root = n;
            i = ii;
            l = ll;
            r = rr;
        }
        TreeNode root;
        int i, l, r;
    }
    public List < List < String >> printTree(TreeNode root) {
        int height = getHeight(root);
        System.out.println(height);
        String[][] res = new String[height][(1 << height) - 1];
        for (String[] arr: res)
            Arrays.fill(arr, "");
        List < List < String >> ans = new ArrayList < > ();
        fill(res, root, 0, 0, res[0].length);
        for (String[] arr: res)
            ans.add(Arrays.asList(arr));
        return ans;
    }
    public void fill(String[][] res, TreeNode root, int i, int l, int r) {
        Queue < Params > queue = new LinkedList();
        queue.add(new Params(root, 0, 0, res[0].length));
        while (!queue.isEmpty()) {
            Params p = queue.remove();
            res[p.i][(p.l + p.r) / 2] = "" + p.root.val;
            if (p.root.left != null)
                queue.add(new Params(p.root.left, p.i + 1, p.l, (p.l + p.r) / 2));
            if (p.root.right != null)
                queue.add(new Params(p.root.right, p.i + 1, (p.l + p.r + 1) / 2, p.r));
        }
    }
    public int getHeight(TreeNode root) {
        Queue < TreeNode > queue = new LinkedList();
        queue.add(root);
        int height = 0;
        while (!queue.isEmpty()) {
            height++;
            Queue < TreeNode > temp = new LinkedList();
            while (!queue.isEmpty()) {
                TreeNode node = queue.remove();
                if (node.left != null)
                    temp.add(node.left);
                if (node.right != null)
                    temp.add(node.right);
            }
            queue = temp;
        }
        return height;
    }
}

Complexity Analysis

  • Time complexity : O(h*2^h)O(h2h). We need to fill the resres array of size hhx2^h - 12h1. Here, hh refers to the height of the given tree.

  • Space complexity : O(h*2^h)O(h2h)resres array of size hhx2^h - 12h1 is used.


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值