Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/655.html

655. Print Binary Tree (Medium)

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

Companies:
Uber, Microsoft

Related Topics:
Tree

Solution 1.

// OJ: https://leetcode.com/problems/print-binary-tree/
// Time: O(N)
// Space: O(N)
class Solution {
private:
    int getDepth(TreeNode *root) {
        queue<TreeNode*> q;
        int d = 0;
        q.push(root);
        while (q.size()) {
            int cnt = q.size();
            while (cnt--) {
                root = q.front();
                q.pop();
                if (root->left) q.push(root->left);
                if (root->right) q.push(root->right);
            }
            ++d;
        }
        return d;
    }
    void dfs(TreeNode *root, int start, int end, int depth, vector<vector<string>> &ans) {
        if (!root) return;
        int M = (start + end) / 2;
        ans[depth][M] = to_string(root->val);
        dfs(root->left, start, M, depth + 1, ans);
        dfs(root->right, M + 1, end, depth + 1, ans);
    }
public:
    vector<vector<string>> printTree(TreeNode* root) {
        int d = getDepth(root), N = (1 << d) - 1;
        vector<vector<string>> ans(d, vector<string>(N));
        dfs(root, 0, N, 0, ans);
        return ans;
    }
};

Java

  • /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public List<List<String>> printTree(TreeNode root) {
            if (root == null)
                return new ArrayList<List<String>>();
            List<List<int[]>> valuePositionList = new ArrayList<List<int[]>>();
            Queue<TreeNode> nodeQueue = new LinkedList<TreeNode>();
            nodeQueue.offer(root);
            Queue<Integer> positionQueue = new LinkedList<Integer>();
            positionQueue.offer(0);
            while (!nodeQueue.isEmpty()) {
                List<int[]> curRow = new ArrayList<int[]>();
                int size = nodeQueue.size();
                for (int i = 0; i < size; i++) {
                    TreeNode node = nodeQueue.poll();
                    int position = positionQueue.poll();
                    int[] valuePosition = {node.val, position};
                    curRow.add(valuePosition);
                    TreeNode left = node.left, right = node.right;
                    if (left != null) {
                        nodeQueue.offer(left);
                        positionQueue.offer(position * 2);
                    }
                    if (right != null) {
                        nodeQueue.offer(right);
                        positionQueue.offer(position * 2 + 1);
                    }
                }
                valuePositionList.add(curRow);
            }
            List<List<String>> print = new ArrayList<List<String>>();
            int size = valuePositionList.size();
            int rowLength = (int) Math.pow(2, size) - 1;
            int difference = rowLength + 1;
            for (int i = 0; i < size; i++) {
                List<String> curRowPrint = new ArrayList<String>();
                for (int j = 0; j < rowLength; j++)
                    curRowPrint.add("");
                List<int[]> rowValuePosition = valuePositionList.get(i);
                int start = difference / 2 - 1;
                for (int[] valuePosition : rowValuePosition) {
                    int value = valuePosition[0], position = valuePosition[1];
                    int index = start + position * difference;
                    curRowPrint.set(index, String.valueOf(value));
                }
                print.add(curRowPrint);
                difference /= 2;
            }
            return print;
        }
    }
    
  • // OJ: https://leetcode.com/problems/print-binary-tree/
    // Time: O(N)
    // Space: O(N)
    class Solution {
    private:
        int getDepth(TreeNode *root) {
            queue<TreeNode*> q;
            int d = 0;
            q.push(root);
            while (q.size()) {
                int cnt = q.size();
                while (cnt--) {
                    root = q.front();
                    q.pop();
                    if (root->left) q.push(root->left);
                    if (root->right) q.push(root->right);
                }
                ++d;
            }
            return d;
        }
        void dfs(TreeNode *root, int start, int end, int depth, vector<vector<string>> &ans) {
            if (!root) return;
            int M = (start + end) / 2;
            ans[depth][M] = to_string(root->val);
            dfs(root->left, start, M, depth + 1, ans);
            dfs(root->right, M + 1, end, depth + 1, ans);
        }
    public:
        vector<vector<string>> printTree(TreeNode* root) {
            int d = getDepth(root), N = (1 << d) - 1;
            vector<vector<string>> ans(d, vector<string>(N));
            dfs(root, 0, N, 0, ans);
            return ans;
        }
    };
    
  • # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, val=0, left=None, right=None):
    #         self.val = val
    #         self.left = left
    #         self.right = right
    class Solution:
        def printTree(self, root: Optional[TreeNode]) -> List[List[str]]:
            def height(root):
                if root is None:
                    return -1
                return 1 + max(height(root.left), height(root.right))
    
            def dfs(root, r, c):
                if root is None:
                    return
                ans[r][c] = str(root.val)
                dfs(root.left, r + 1, c - 2 ** (h - r - 1))
                dfs(root.right, r + 1, c + 2 ** (h - r - 1))
    
            h = height(root)
            m, n = h + 1, 2 ** (h + 1) - 1
            ans = [[""] * n for _ in range(m)]
            dfs(root, 0, (n - 1) // 2)
            return ans
    
    ############
    
    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
      def printTree(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[str]]
        """
    
        def height(root):
          if not root:
            return 0
          return 1 + max(height(root.left), height(root.right))
    
        def fill(root, res, left, right, h):
          if root:
            val = str(root.val)
            mid = left + (right - left) / 2
            res[h][mid] = val
            fill(root.left, res, left, mid - 1, h + 1)
            fill(root.right, res, mid + 1, right, h + 1)
    
        h = height(root)
        res = [[""] * (2 ** h - 1) for _ in range(h)]
        fill(root, res, 0, len(res[0]) - 1, 0)
        return res
    
    

All Problems

All Solutions