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

LeetCode 103:Binary Tree Zigzag Level Order Traversal

时间:2017-08-20 22:27:37      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:its   serial   fonts   翻转   word   targe   level   etc   tween   

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

confused what "{1,#,2,3}" means?

 > read more on how binary tree is serialized on OJ.

Subscribe to see which companies asked this question

 //递归方法:用一个bool记录是从左到右还是从右到左。每一层结束就翻转一下。

class Solution { public: vector<vector<int>> zigzagLevelOrder(TreeNode* root) { vector<vector<int>> res; traverse(root, 1, res, true); return res; } void traverse(TreeNode* root, int level, vector<vector<int>> &res, bool left_to_right){ if (!root) return; if (level > res.size()) res.push_back(vector<int>()); if (left_to_right) res[level - 1].push_back(root->val); else res[level - 1].insert(res[level - 1].begin(), root->val); traverse(root->left, level + 1, res, !left_to_right); traverse(root->right, level + 1, res, !left_to_right); } };


技术分享

LeetCode 103:Binary Tree Zigzag Level Order Traversal

标签:its   serial   fonts   翻转   word   targe   level   etc   tween   

原文地址:http://www.cnblogs.com/mfmdaoyou/p/7401349.html

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