Created
December 29, 2012 13:31
-
-
Save pdu/4406972 to your computer and use it in GitHub Desktop.
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
http://www.leetcode.com/onlinejudge
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Definition for binary tree | |
| * struct TreeNode { | |
| * int val; | |
| * TreeNode *left; | |
| * TreeNode *right; | |
| * TreeNode(int x) : val(x), left(NULL), right(NULL) {} | |
| * }; | |
| */ | |
| class Solution { | |
| public: | |
| void bfs(vector< vector<int> >& ret, int& maxDepth, int curDepth, TreeNode* node) { | |
| if (node == NULL) { | |
| return; | |
| } | |
| if (curDepth > maxDepth) { | |
| ret.resize(curDepth + 1); | |
| maxDepth = curDepth; | |
| } | |
| ret[curDepth].push_back(node->val); | |
| bfs(ret, maxDepth, curDepth + 1, node->left); | |
| bfs(ret, maxDepth, curDepth + 1, node->right); | |
| } | |
| vector<vector<int> > levelOrder(TreeNode *root) { | |
| vector< vector<int> > ret; | |
| int maxDepth = -1; | |
| bfs(ret, maxDepth, 0, root); | |
| return ret; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment