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

Rust Solution

struct Solution;
use rustgym_util::*;

trait Postorder {
    fn height(&self) -> usize;
}

impl Postorder for TreeLink {
    fn height(&self) -> usize {
        if let Some(node) = self {
            let left = &node.borrow().left;
            let right = &node.borrow().right;
            1 + left.height().max(right.height())
        } else {
            0
        }
    }
}

trait Preorder {
    fn print(&self, i: usize, j: usize, grid: &mut Vec<Vec<String>>, w: usize, h: usize);
}

impl Preorder for TreeLink {
    fn print(&self, i: usize, j: usize, grid: &mut Vec<Vec<String>>, w: usize, h: usize) {
        if let Some(node) = self {
            let left = &node.borrow().left;
            let right = &node.borrow().right;
            let val = node.borrow().val;
            grid[i][j] = format!("{}", val);
            if i != h - 1 {
                let left_index = j - (w >> 2) - 1;
                let right_index = j + (w >> 2) + 1;
                left.print(i + 1, left_index, grid, w >> 1, h);
                right.print(i + 1, right_index, grid, w >> 1, h);
            }
        }
    }
}

impl Solution {
    fn print_tree(root: TreeLink) -> Vec<Vec<String>> {
        let h = root.height();
        let w = (1 << h) - 1;
        let mut res = vec![vec!["".to_string(); w]; h];
        root.print(0, w >> 1, &mut res, w, h);
        res
    }
}

#[test]
fn test() {
    let root = tree!(1, tree!(2), None);
    let res = vec_vec_string![["", "1", ""], ["2", "", ""]];
    assert_eq!(Solution::print_tree(root), res);
    let root = tree!(1, tree!(2, None, tree!(4)), tree!(3));
    let res = vec_vec_string![
        ["", "", "", "1", "", "", ""],
        ["", "2", "", "", "", "3", ""],
        ["", "", "4", "", "", "", ""]
    ];
    assert_eq!(Solution::print_tree(root), res);
    let root = tree!(1, tree!(2, tree!(3, tree!(4), None), None), tree!(5));
    let res = vec_vec_string![
        ["", "", "", "", "", "", "", "1", "", "", "", "", "", "", ""],
        ["", "", "", "2", "", "", "", "", "", "", "", "5", "", "", ""],
        ["", "3", "", "", "", "", "", "", "", "", "", "", "", "", ""],
        ["4", "", "", "", "", "", "", "", "", "", "", "", "", "", ""]
    ];
    assert_eq!(Solution::print_tree(root), res);
}

Having problems with this solution? Click here to submit an issue on github.