• LeetCode:Binary Tree Zigzag Level Order Traversal


    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 between).

    For example:
    Given binary tree {3,9,20,#,#,15,7},

        3
       / 
      9  20
        /  
       15   7
    

    return its zigzag level order traversal as:

    [
      [3],
      [20,9],
      [15,7]
    ]
    在level的基础上加一个bool变量来记录是否轮到left_toright.
     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
    13         vector<vector<int>> result;
    14         traversal(root,1,result,true);
    15         return result;
    16     }
    17     
    18     void traversal(TreeNode *node,int level,vector<vector<int>> &result,bool left_toright)
    19     {
    20         
    21         if(node==NULL) return;
    22         if(level>result.size())
    23             result.push_back(vector<int>());  //不可以缺少
    24         if(left_toright)
    25         {
    26             result[level-1].push_back(node->val);
    27         }
    28         else{
    29             result[level-1].insert(result[level-1].begin(),node->val);
    30         }
    31         
    32         traversal(node->left,level+1,result,!left_toright);
    33         traversal(node->right,level+1,result,!left_toright);
    34         
    35         
    36     }
    37     
    38 };
  • 相关阅读:
    git基本使用
    list和tuple
    牛客(60)把二叉树打印成多行
    牛客(59)按之字形顺序打印二叉树
    牛客(58)对称的二叉树
    牛客(57)二叉树的下一个结点
    牛客(56)删除链表中重复的结点
    牛客(55)链表中环的入口结点
    mybits(1)配置
    牛客(53)表示数值的字符串
  • 原文地址:https://www.cnblogs.com/xiaoying1245970347/p/4726262.html
Copyright © 2020-2023  润新知