zoukankan      html  css  js  c++  java
  • LeetCode OJ

    题目:

    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]
    ]

    解题思路:

    深度优先遍历

    代码:

     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 
    11 class Solution {
    12 public:
    13     vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
    14         vector<vector<int>> ans;
    15         if (root == NULL) return ans;
    16 
    17         vector<TreeNode *> one, another;
    18         one.push_back(root);
    19 
    20         while (!one.empty() || !another.empty()) {
    21             if (!one.empty()) {
    22                 vector<int> cur_ans;
    23                 TreeNode * node = NULL;
    24                 for (int i = 0; i < one.size(); i++) {
    25                     node = one[i];
    26                     cur_ans.push_back(node->val);
    27                     if (node->left) another.push_back(node->left);
    28                     if (node->right) another.push_back(node->right);
    29                 }
    30                 ans.push_back(cur_ans);
    31                 one.clear();
    32             }
    33             if (!another.empty()) {
    34                 vector<int> cur_ans;
    35                 TreeNode * node = NULL;
    36                 for (int i = 0; i < another.size(); i++) {
    37                     node = another[i];
    38                     cur_ans.push_back(node->val);
    39                     if (node->left) one.push_back(node->left);
    40                     if (node->right) one.push_back(node->right);
    41                 }
    42                 reverse(cur_ans.begin(), cur_ans.end());
    43                 ans.push_back(cur_ans);
    44                 another.clear();
    45             }
    46         }
    47         return ans;
    48     }
    49 };
  • 相关阅读:
    2016 Multi-University Training Contest 5 ATM Mechine
    2016 Multi-University Training Contest 5 Divide the Sequence
    UVA 10082 WERTYU
    UVA 272 TEX Quotes
    紫书理解
    Codeforces Round #363 (Div. 2) One Bomb
    BestCoder Round #85 hdu5778 abs(素数筛+暴力)
    计算几何模板
    BestCoder Round #85 hdu5777 domino
    BestCoder Round #85 hdu5776 sum
  • 原文地址:https://www.cnblogs.com/dongguangqing/p/3728256.html
Copyright © 2011-2022 走看看