Print a binary tree in an m*n 2D string array following these 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].
给定一颗二叉树,按照格式打印这个树。
这道题的输出是一个二维数组,我们可以观察到,数组的高度等于树的高度h,宽度等于2^h-1,所以针对这道题,我们要先求出给定树的高度,再开辟相应大小的数组。
其次我们再观察,根节点处于二维数组第一行的中间,将左右两边均等的分开,其左右子树的根节点分别位于分开的两行的中间,可以想到使用递归来实现。
每次填充时传递一个高度参数用来锁定二维数组的行号。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<string>> printTree(TreeNode* root) { int h = getTreeH(root); //w = 2^h-1 int w = (1<<h)-1; vector<vector<string>> res(h, vector<string>(w)); printTree(root, res, 0, 0, w-1); return res; } void printTree(TreeNode* root, vector<vector<string>>& res, int h, int l, int r){ if(!root) return; int mid = (l+r)/2; res[h][mid] = to_string(root->val); printTree(root->left, res, h+1, l, mid-1); printTree(root->right, res, h+1, mid+1, r); } //get tree height int getTreeH(TreeNode* root){ if(!root) return 0; return max(getTreeH(root->left), getTreeH(root->right))+1; } };
LeetCode 655. Print Binary Tree (C++)
原文:https://www.cnblogs.com/silentteller/p/10721048.html