参见 http://www.geeksforgeeks.org/print-binary-tree-vertical-order/
1 首先定义 Vertical Order,
1
/ \
2 3
/ \ / \
4 5 6 7
\ \
8 9
The output of print this tree vertically will be:
4 :
2
1 5 6
3 8
7
9
因为
4 : 与root的距离为-2
2: 与root的距离为-1
1 5 6: 与root的距离为0
3 8: 与root的距离为1
7: 与root的距离为2
9 : 与root的距离为3
所以按照和root的距离从远到近的顺序排列下来,就是上面所示的打印结果。
2 代码如下:
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
void get_min_max(TreeNode* root, int & min, int & max, int current_distance ) {
if (root == NULL) return;
if (current_distance < min) min = current_distance;
if (current_distance > max) max = current_distance;
get_min_max(root->left, min, max, current_distance - 1);
get_min_max(root->right, min, max, current_distance + 1);
}
void helper(TreeNode* root, int line_index, int current_distance) {
if (root == NULL) return;
if(line_index == current_distance) {
std::cout<<root->val<<", ";
}
helper(root->left, line_index, current_distance - 1);
helper(root->right, line_index, current_distance + 1);
}
void vertical_tra(TreeNode* root) {
int min;
int max;
int current_distance = 0;
get_min_max(root, min, max, current_distance);
std::cout<<"min = "<<min<<", max = "<<max<<std::endl;
for (int i = min; i < max; ++i ) {
helper(root, i, current_distance);
std::cout<<std::endl;
}
}
};