Tony's Log

Algorithms, Distributed System, Machine Learning

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

BFS solution is intuitive - here I will show a DFS based solution:

/**
 * 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 {
    int height;
    vector<vector<int>> ret;
    
    int getHeight(TreeNode*p)
    {
        if(!p) return 0;
        return max(getHeight(p->left), getHeight(p->right)) + 1; 
    }
    void go(TreeNode *p, int level)
    {
        if(!p) return;
        ret[height - 1 - level].push_back(p->val);
        go(p->left, level + 1);
        go(p->right, level + 1);
    }
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) 
    {
        if(!root) return ret;
        
        height = getHeight(root);
        ret.assign(height, vector<int>());
        
        go(root, 0);
        return ret;
    }
};
posted on 2016-06-05 10:05  Tonix  阅读(114)  评论(0编辑  收藏  举报