[LeetCode] 655. Print Binary Tree 打印二叉树

二叉树的可视化打印
本文介绍了一种将二叉树以二维数组形式可视化打印的方法,通过递归算法确定二叉树的高度和宽度,实现了左子树和右子树的均衡布局。

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].

给一个二叉树,按照以下规则以m * n二维数组的形式打印出来:

1. 行号m应该等于给定二叉树的高度。
2. 列号n应始终为奇数。
3. 根节点的值(以字符串格式)应该放在它可以放入的第一行的正中间。 根节点所属的列和行将剩余空间分成两部分(左下部分和右下部分)。 您应该在左下部分打印左子树,并在右下部分打印右子树。 左下部和右下部应具有相同的尺寸。 即使一个子树不是,而另一个子树不是,你也不需要为无子树打印任何东西,但仍然需要留出与其他子树一样大的空间。 但是,如果两个子树都没有,那么您不需要为它们留出空间。
4. 每个未使用的空间应包含一个空字符串""。
5. 按照相同的规则打印子树。

解法:递归(Recursion),首先求出二叉树的深度来确定列,二维数组的列是2 ** height -1,height是二叉树深度。然后递归处理每一层,每一行中根节点的位置是:pos-2**(height - h - 1),pos是上一层的根节点的位置。

Java:

public List<List<String>> printTree(TreeNode root) {
    List<List<String>> res = new LinkedList<>();
    int height = root == null ? 1 : getHeight(root);
    int rows = height, columns = (int) (Math.pow(2, height) - 1);
    List<String> row = new ArrayList<>();
    for(int i = 0; i < columns; i++)  row.add("");
    for(int i = 0; i < rows; i++)  res.add(new ArrayList<>(row));
    populateRes(root, res, 0, rows, 0, columns - 1);
    return res;
}

public void populateRes(TreeNode root, List<List<String>> res, int row, int totalRows, int i, int j) {
    if (row == totalRows || root == null) return;
    res.get(row).set((i+j)/2, Integer.toString(root.val));
    populateRes(root.left, res, row+1, totalRows, i, (i+j)/2 - 1);
    populateRes(root.right, res, row+1, totalRows, (i+j)/2+1, j);
}

public int getHeight(TreeNode root) {
     if (root == null) return 0;
     return 1 + Math.max(getHeight(root.left), getHeight(root.right));
}

Python:

class Solution(object):
    def printTree(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[str]]
        """
        def get_height(node):
            return 0 if not node else 1 + max(get_height(node.left), get_height(node.right))
        
        def update_output(node, row, left, right):
            if not node:
                return
            mid = (left + right) / 2
            self.output[row][mid] = str(node.val)
            update_output(node.left, row + 1 , left, mid - 1)
            update_output(node.right, row + 1 , mid + 1, right)
            
        height = get_height(root)
        width = 2 ** height - 1
        self.output = [[''] * width for i in xrange(height)]
        update_output(node=root, row=0, left=0, right=width - 1)
        return self.output

Python:  

class Solution(object):
    def printTree(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[str]]
        """
        def get_height(node):
            if not node:
                return 0
            return 1 + max(get_height(node.left), get_height(node.right))

        rows = get_height(root)
        cols = 2 ** rows - 1
        res = [['' for _ in range(cols)] for _ in range(rows)]

        def traverse(node, level, pos):
            if not node:
                return
            left_padding, spacing = 2 ** (rows - level - 1) - 1, 2 ** (rows - level) - 1
            index = left_padding + pos * (spacing + 1)
            print(level, index, node.val)
            res[level][index] = str(node.val)
            traverse(node.left, level + 1, pos << 1)
            traverse(node.right, level + 1, (pos << 1) + 1)
        traverse(root, 0, 0)
        return res  

Python:

class Solution(object):
    def printTree(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[str]]
        """
        import math
        def dfs(root, h):
            if root:
                return max(dfs(root.left,h+1), dfs(root.right,h+1))
            else :
                return h
        height = dfs(root, 0)
        width = 2 ** height -1
        # 初始化
        res = [ ["" for j in range(width)] for i in range(height)]
        # dfs print
        def dfs_print(res,root,h,pos):
            if root:
                res[h - 1][pos] = '%d' % root.val
                dfs_print(res, root.left, h+1, pos-2**(height - h - 1))
                dfs_print(res, root.right, h+1, pos+2**(height - h - 1))
        dfs_print(res,root,1,width/2)
        return res

Python:

# Time:  O(h * 2^h)
# Space: O(h * 2^h)
class Solution(object):
    def printTree(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[str]]
        """
        def getWidth(root):
            if not root:
                return 0
            return 2 * max(getWidth(root.left), getWidth(root.right)) + 1

        def getHeight(root):
            if not root:
                return 0
            return max(getHeight(root.left), getHeight(root.right)) + 1

        def preorderTraversal(root, level, left, right, result):
            if not root:
                return
            mid = left + (right-left)/2
            result[level][mid] = str(root.val)
            preorderTraversal(root.left, level+1, left, mid-1, result)
            preorderTraversal(root.right, level+1, mid+1, right, result)

        h, w = getHeight(root), getWidth(root)
        result = [[""] * w for _ in xrange(h)]
        preorderTraversal(root, 0, 0, w-1, result)
        return result

C++:  

class Solution {
public:
    vector<vector<string>> printTree(TreeNode* root) {
        int h = getHeight(root), w = pow(2, h) - 1;
        vector<vector<string>> res(h, vector<string>(w, ""));
        helper(root, 0, w - 1, 0, h, res);
        return res;
    }
    void helper(TreeNode* node, int i, int j, int curH, int height, vector<vector<string>>& res) {
        if (!node || curH == height) return;
        res[curH][(i + j) / 2] = to_string(node->val);
        helper(node->left, i, (i + j) / 2, curH + 1, height, res);
        helper(node->right, (i + j) / 2 + 1, j, curH + 1, height, res);
    }
    int getHeight(TreeNode* node) {
        if (!node) return 0;
        return 1 + max(getHeight(node->left), getHeight(node->right));
    }
};

C++:

class Solution {
public:
    vector<vector<string>> printTree(TreeNode* root) {
        int h = getHeight(root), w = pow(2, h) - 1, curH = -1;
        vector<vector<string>> res(h, vector<string>(w, ""));
        queue<TreeNode*> q{{root}};
        queue<pair<int, int>> idxQ{{{0, w - 1}}};
        while (!q.empty()) {
            int n = q.size();
            ++curH;
            for (int i = 0; i < n; ++i) {
                auto t = q.front(); q.pop();
                auto idx = idxQ.front(); idxQ.pop();
                if (!t) continue;
                int left = idx.first, right = idx.second;
                int mid = left + (right - left) / 2;
                res[curH][mid] = to_string(t->val);
                q.push(t->left);
                q.push(t->right);
                idxQ.push({left, mid});
                idxQ.push({mid + 1, right});
            }
        }
        return res;
    }
    int getHeight(TreeNode* node) {
        if (!node) return 0;
        return 1 + max(getHeight(node->left), getHeight(node->right));
    }
};

  

  

  

 

All LeetCode Questions List 题目汇总

转载于:https://www.cnblogs.com/lightwindy/p/9859912.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值