Leetcode Note: Binary Tree Zigzag Level Order Traversal

Source: Internet
Author: User

Leetcode Note: Binary Tree Zigzag Level Order Traversal

I. Description

Given a binary tree, return the zigzag level order traversal of its nodes 'values. (ie, from left to right, then right to left for the next level and alternate ).
For example: Given binary tree, 20,

   3  /   9 20    /    15  7

Ii. Question Analysis

BFS. Here, a bool record is used to read data from left to right or from right to left. After each layer traversal ends, it is flipped.

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
    
      > zigzagLevelOrder(TreeNode *root)    {        vector
     
       > result;        Traverse(root, 1, result, true);        return result;    }private:    void Traverse(TreeNode *root, size_t level, vector
      
        > & result, bool leftToRight) { if (root == NULL) return; if (level > result.size()) result.push_back(vector
       
        ()); if (leftToRight) result[level - 1].push_back(root->val); else result[level - 1].insert(result[level - 1].begin(), root->val); Traverse(root->left, level + 1, result, !leftToRight); Traverse(root->right, level + 1, result, !leftToRight); }};
       
      
     
    
   
  

Iv. Summary

It is a little more difficult than Binary Tree Level Order Traversal and Binary Tree Level Order Traversal II. Pay attention to more details.

 

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.