zoukankan      html  css  js  c++  java
  • LeetCode: Binary Tree Zigzag Level Order Traversal

    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]
    ]
    
    地址:https://oj.leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
    算法:变着花样来遍历一颗树,二叉树都快被玩坏了。还是在二叉树层次遍历的结果上进行处理。代码:
     1 /**
     2  * Definition for binary tree
     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         if(!root)   return vector<vector<int> >();
    14         queue<TreeNode *> que;
    15         que.push(root);
    16         int push_num = 1;
    17         int pop_num  = 0;
    18         vector<vector<int> > result;
    19         vector<int> temp;
    20         int last  = 1;
    21         while(!que.empty()){
    22             TreeNode *pop_node = que.front();
    23             temp.push_back(pop_node->val);
    24             que.pop();
    25             ++pop_num;
    26             if(pop_node->left){
    27                 que.push(pop_node->left);
    28                 ++push_num;
    29             }
    30             if(pop_node->right){
    31                 que.push(pop_node->right);
    32                 ++push_num;
    33             }
    34             if(pop_num == last){
    35                 result.push_back(temp);
    36                 temp.clear();
    37                 last = push_num;
    38             }
    39         }
    40         for(int i = 1; i < result.size(); i += 2){
    41             int len = result[i].size();
    42             int half_len = len / 2;
    43             for(int j = 0; j < half_len; ++j){
    44                 int t = result[i][j];
    45                 result[i][j] = result[i][len-j-1];
    46                 result[i][len-j-1] = t;
    47             }
    48         }
    49         return result;
    50     }
    51 };
  • 相关阅读:
    pytest实现参数化(@pytest.mark.parametrize)
    pytest标记测试用例为预期失败(@pytest.mark.xfail)
    pytest标记跳过某些测试用例不执行
    pytest的conftest.py配置
    pytest之fixture使用
    模拟赛42 题解
    模拟赛41 题解
    一些可能永远用不到的性质
    补锅
    骗分杂谈
  • 原文地址:https://www.cnblogs.com/boostable/p/leetcode_binary_tree_zigzag_level_order_traversal.html
Copyright © 2011-2022 走看看