Leetcode Note: Binary Tree Level Order Traversal II

Source: Internet
Author: User

Leetcode Note: Binary Tree Level Order Traversal II

I. Description

Given a binary tree, return the bottom-up level order traversal of its nodes 'values. (ie, from left to right, level by level from leaf to root ).
For example: Given binary tree {, 20, #, #, 15, 7 },

   3  /   9 20    /    15  7

Ii. Question Analysis

Because vector is used, you only need to add a reverse (result. begin (), result. end () on the basis of Binary Tree Level Order Traversal. This is the beauty of programming in the impression.

Iii. Sample Code

# 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
    
     
> LevelOrderBottom (TreeNode * root) {vector
     
      
> Result; orderTraversal (root, 1, result); reverse (result. begin (), result. end (); // Add return result;} private: void orderTraversal (TreeNode * root, size_t level, vector
      
        > & Result) {if (root = NULL) return; if (level> result. size () result. 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 solution is the same as Binary Tree Level Order Traversal. There are also many solutions that need to be carefully studied.

 

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.