diff options
Diffstat (limited to 'binary_tree_level_traverse.cpp')
-rw-r--r-- | binary_tree_level_traverse.cpp | 31 |
1 files changed, 31 insertions, 0 deletions
diff --git a/binary_tree_level_traverse.cpp b/binary_tree_level_traverse.cpp new file mode 100644 index 0000000..47a69da --- /dev/null +++ b/binary_tree_level_traverse.cpp @@ -0,0 +1,31 @@ +#include "leetcode.h" + +class Solution { +public: + vector<vector<int>> levelOrder(TreeNode *root) { + vector<vector<int>> ans; + if (!root) + return ans; + queue<TreeNode *> q; + q.push(root); + q.push(NULL); + vector<int> curr; + while (!q.empty()) { + TreeNode *t = q.front(); + q.pop(); + if (t == NULL) { + ans.push_back(curr); + curr.resize(0); + if (q.size() > 0) + q.push(NULL); + } else { + curr.push_back(t->val); + if (t->left) + q.push(t->left); + if (t->right) + q.push(t->right); + } + } + return ans; + } +}; |