#Leetcode# 103. Binary Tree Zigzag Level Order Traversal

Posted 丧心病狂工科女

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了#Leetcode# 103. Binary Tree Zigzag Level Order Traversal相关的知识,希望对你有一定的参考价值。

https://leetcode.com/problems/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,null,null,15,7],

    3
   /   9  20
    /     15   7

 

return its zigzag level order traversal as:

[
  [3],
  [20,9],
  [15,7]
]

代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int> > ans;
        if(!root) return ans;
        level(root, ans, 1);
        for(int i = 0; i < ans.size(); i ++) {
            if(i % 2) {
                for(int j = 0; j < ans[i].size() / 2; j ++)
                    swap(ans[i][j], ans[i][ans[i].size() - j - 1]);
            }
        }
        return ans;
    }
    void level(TreeNode* root, vector<vector<int> >& ans, int depth) {
        vector<int> v;
        if(depth > ans.size()) {
            ans.push_back(v);
            v.clear();
        }
        ans[depth - 1].push_back(root -> val);
        if(root -> left)
            level(root -> left, ans, depth + 1);
        if(root -> right)
            level(root -> right, ans, depth + 1);
    }
};

  


以上是关于#Leetcode# 103. Binary Tree Zigzag Level Order Traversal的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode]题解(python):103 Binary Tree Zigzag Level Order Traversal

LeetCode103. Binary Tree Zigzag Level Order Traversal 解题报告

一天一道LeetCode#103. Binary Tree Zigzag Level Order Traversal

[LeetCode]题解(python):103-Binary Tree Zigzag Level Order Traversal

leetcode-----103. 二叉树的锯齿形层次遍历

Leetcode 103. Binary Tree Zigzag Level Order Traversal