16
05/2015
[LeetCode] Binary Tree Level Order Traversal
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] ]
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
解题思路:
用一个队列记录所有的节点。但是这里有个陷阱就是每一层应该分别用一个vector表示,因此还需要一个队列来存储对应的node所在的层数。因为同一层在队列中肯定是相邻的,因此可以通过这种方法来解决。
/** * 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 { public: vector<vector<int>> levelOrder(TreeNode* root) { vector<vector<int>> result; if(root==NULL){ return result; } queue<int> level; queue<TreeNode*> queues; level.push(0); queues.push(root); int lastLevel = 0; vector<int> lastValue; while(!queues.empty()){ TreeNode* node = queues.front(); int l = level.front(); if(l!=lastLevel){ result.push_back(lastValue); lastValue.clear(); lastLevel = l; } lastValue.push_back(node->val); queues.pop(); level.pop(); if(node->left!=NULL){ queues.push(node->left); level.push(l + 1); } if(node->right!=NULL){ queues.push(node->right); level.push(l + 1); } } if(!lastValue.empty()){ result.push_back(lastValue); } return result; } };
二次刷题(2015-08-03)
用两个队列来存储中间结果。
/** * 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 { public: vector<vector<int>> levelOrder(TreeNode* root) { vector<vector<int>> result; if(root==NULL){ return result; } queue<TreeNode*> q[2]; int k = 0; q[0].push(root); while(!q[k].empty()){ vector<int> item; while(!q[k].empty()){ TreeNode* node = q[k].front(); q[k].pop(); item.push_back(node->val); if(node->left!=NULL){ q[(k+1)%2].push(node->left); } if(node->right!=NULL){ q[(k+1)%2].push(node->right); } } k = (k+1)%2; result.push_back(item); } return result; } };
用深度优先遍历来实现
/** * 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 { public: vector<vector<int>> levelOrder(TreeNode* root) { int h = getHeight(root); vector<vector<int>> result(h, vector<int>()); DFSTraversal(root, 0, result); return result; } void DFSTraversal(TreeNode* root, int level, vector<vector<int>>& result){ if(root!=NULL){ result[level].push_back(root->val); DFSTraversal(root->left, level+1, result); DFSTraversal(root->right, level+1, result); } } int getHeight(TreeNode* root){ if(root==NULL){ return 0; } return 1 + max(getHeight(root->left), getHeight(root->right)); } };
0 条评论