码迷,mamicode.com
首页 > 其他好文 > 详细

#Leetcode# 103. Binary Tree Zigzag Level Order Traversal

时间:2018-12-18 22:40:22      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:ems   struct   alter   div   pre   from   binary   str   public   

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

标签:ems   struct   alter   div   pre   from   binary   str   public   

原文地址:https://www.cnblogs.com/zlrrrr/p/10140283.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!