• 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 };
  • 相关阅读:
    Object.prototype的原型对象 格式化日期【js笔记】
    数组中去掉重复的 【js笔记】
    按照内容多少,每行自动按照内容较多的div设置其他div的高度【jq笔记】
    动态操作表格 【js笔记】
    关于记录任意选择行删除或者其他的操作【jq笔记】
    Good studying and day day up
    第三周星期一
    第二周星期天
    第二周星期六
    第二周星期五
  • 原文地址:https://www.cnblogs.com/dongguangqing/p/3728256.html
Copyright © 2020-2023  润新知