首页 > 其他 > 详细

LeetCode "Find Leaves of Binary Tree"

时间:2016-06-27 12:02:50      阅读:365      评论:0      收藏:0      [点我收藏+]

Typical DFS problem. Simply get higher height and push_back.

/**
 * 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 {
    vector<vector<int>> ret;
    int go(TreeNode *p) // return max height
    {
        if(!p) return 0;
        
        int hl = go(p->left);
        int hr = go(p->right);
        
        int h = max(hl, hr) + 1;
        if(h > ret.size()) ret.push_back({});
        ret[h - 1].push_back(p->val);
        
        return h;
    }
public:
    vector<vector<int>> findLeaves(TreeNode* root) {
        go(root);
        return ret;
    }
};

LeetCode "Find Leaves of Binary Tree"

原文:http://www.cnblogs.com/tonix/p/5619696.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!