I. Title Description
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},
9 20 15 7
Two. Topic analysis
No.
Three. Sample code
Referring to the practice of Stellari in discussion, recursive hierarchy traversal, and each level corresponds to the corresponding vector:
#include <iostream>#include <vector>using namespace STD;structtreenode{intVal TreeNode *left; TreeNode *right; TreeNode (intx): Val (x), left (null), right (null) {}};classSolution { Public: vector<vector<int> >Levelorder (TreeNode *root) { vector<vector<int> >Result Ordertraversal (Root,1, result);returnResult }Private:voidOrdertraversal (treenode* root,intLevel vector<vector<int> >& result) {if(Root = NULL)return;if(Level > Result.size ())//Each down level, create an empty vector to save the layer dataResult.push_back ( vector<int>()); Result[level-1].push_back (Root->val); Ordertraversal (Root->left, Level +1, result); Ordertraversal (Root->right, Level +1, result); }};
Four. Summary
The above is recursive implementation, can also be written as iteration version, time complexity O (n), Space complexity O (1).
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode Note: Binary Tree level Order traversal