LeetCode-102-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,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
解题思路:二叉树水平序列访问,用队列辅助。
vector<vector<int>> levelOrder(TreeNode* root) { vector<vector<int>> results; helper(root,results,0); return results; } void helper(TreeNode* root, vector<vector<int>>& results, int level){ if(root == nullptr) return; if(results.size() <= level){ vector<int> temp; results.push_back(temp); } results[level].push_back(root->val); helper(root->left, results,level+1); helper(root->right,results,level+1); }