Print A Tree In Vertical Order

参见  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

因为

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;
        }
        
    }
};





 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值