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

Binary Tree Zigzag Level Order Traversal

时间:2015-12-18 10:26:59      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:

Binary Tree Zigzag Level Order Traversal

Total Accepted: 49079 Total Submissions: 179977 Difficulty: Medium

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]
]
/**
 * 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:
    void preorder(TreeNode* root,vector<vector<int>>& res,int depth){
        if(!root) return;
        if(depth==res.size()){
            res.push_back(vector<int>());
        }
        if(depth&1) {
            res[depth].insert(res[depth].begin(),root->val);
        }else{
            res[depth].push_back(root->val);
        }
        preorder(root->left,res,depth+1);
        preorder(root->right,res,depth+1);
    }
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> res;
        preorder(root,res,0);
        return res;
    }
};

Binary Tree Zigzag Level Order Traversal

标签:

原文地址:http://www.cnblogs.com/zengzy/p/5056168.html

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