Leetcode Note: Binary Tree level Order traversal

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.