Skip to content

Commit

Permalink
Binary Tree Level Order Traversal: add dfs solution
Browse files Browse the repository at this point in the history
  • Loading branch information
moophis committed Oct 8, 2014
1 parent 2276397 commit 4866157
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions Binary Tree Level Order Traversal.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
* ]
*/

// dfs
/**
* Definition for binary tree
* struct TreeNode {
Expand All @@ -26,6 +27,30 @@
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
void dfs(TreeNode *root, vector<vector<int> > &ret, int level) {
if (root == nullptr) {
return;
}
if (level >= ret.size()) {
ret.push_back({root->val});
} else {
ret[level].push_back(root->val);
}
dfs(root->left, ret, level + 1);
dfs(root->right, ret, level + 1);
}

public:
vector<vector<int> > levelOrder(TreeNode *root) {
vector<vector<int> > ret;
dfs(root, ret, 0);

return ret;
}
};

// bfs
class Solution {
public:
vector<vector<int> > levelOrder(TreeNode *root) {
Expand Down

0 comments on commit 4866157

Please sign in to comment.