Leetcode Note: Binary Tree Level Order Traversal

Source: Internet
Author: User

Leetcode Note: Binary Tree Level Order Traversal

I. 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 {, 20, #, #, 15, 7 },

  3 /  9 20   /   15  7

Ii. Question Analysis

None.

Iii. Sample Code

Based on the stellari practice in Discussion, recursively traverse layers and map each level to the corresponding vector:

# Include
  
   
# Include
   
    
Using namespace std; struct TreeNode {int val; TreeNode * left; TreeNode * right; TreeNode (int x): val (x), left (NULL), right (NULL) {}}; class Solution {public: vector
    
     
> LevelOrder (TreeNode * root) {vector
     
      
> Result; orderTraversal (root, 1, result); return result;} private: void orderTraversal (TreeNode * root, int level, vector
      
        > & Result) {if (root = NULL) return; if (level> result. size () // create an empty vector next to each level to save the result of this layer of data. push_back (vector
       
         (); Result [level-1]. push_back (root-> val); orderTraversal (root-> left, level + 1, result); orderTraversal (root-> right, level + 1, result );}};
       
      
     
    
   
  

Iv. Summary

The above is a recursive implementation. It can also be written as an iterative version, with time complexity O (n) and space complexity O (1 ).

 

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.