Skip to content

Latest commit

 

History

History
 
 

655. Print Binary Tree

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

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/
// Author: github.com/lzl124631x
// 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;
    }
};