标签:
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; } };
LeetCode "Binary Tree Level Order Traversal II" using DFS
标签:
原文地址:http://www.cnblogs.com/tonix/p/5560174.html