Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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;
    }
};
posted on 2016-06-27 11:35  Tonix  阅读(167)  评论(0)    收藏  举报