Binary Tree Level Order Traversal
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree {3,9,20,#,#,15,7}
,
3 / 9 20 / 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
思路:
这两个题目都很基础,BFS搜索。
题解:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int> > levelOrder(TreeNode *root) { vector<vector<int> > res; vector<int> tmp; queue<TreeNode *> q; int count = 0, num = 1; if(root==NULL) return res; q.push(root); while(!q.empty()) { for(int i=0;i<num;i++) { root = q.front(); q.pop(); tmp.push_back(root->val); if(root->left) { count++; q.push(root->left); } if(root->right) { count++; q.push(root->right); } } res.push_back(tmp); num = count; count = 0; tmp.clear(); } return res; } };
Binary Tree Level Order Traversal II
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree {3,9,20,#,#,15,7}
,
3 / 9 20 / 15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]
题解:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int> > levelOrderBottom(TreeNode *root) { vector<vector<int> > res; vector<int> tmp; queue<TreeNode *> q; int count = 0, num = 1; if(root==NULL) return res; q.push(root); while(!q.empty()) { for(int i=0;i<num;i++) { root = q.front(); q.pop(); tmp.push_back(root->val); if(root->left) { count++; q.push(root->left); } if(root->right) { count++; q.push(root->right); } } res.push_back(tmp); num = count; count = 0; tmp.clear(); } reverse(res.begin(), res.end()); return res; } };