博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode-Binary Tree Zigzag Level Order Traversal
阅读量:5257 次
发布时间:2019-06-14

本文共 1799 字,大约阅读时间需要 5 分钟。

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?

OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

1  / \ 2   3    /   4    \     5

The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".

class Solution {public:    vector
> zigzagLevelOrder(TreeNode *root) { // Note: The Solution object is instantiated only once and is reused by each test case. queue
que; stack
sta; int count=1; int nextCount=0; int level=0; if(root==NULL)return vector
> (); que.push(root); TreeNode* p; vector
> ret; vector
one; while(que.size()!=0){ p=que.front(); que.pop(); if(p->left!=NULL){ que.push(p->left); nextCount++; } if(p->right!=NULL){ que.push(p->right); nextCount++; } count--; if(level%2==0){ one.push_back(p->val); if(count==0){ ret.push_back(one); one.clear(); level++; count=nextCount; nextCount=0; } } else{ sta.push(p->val); if(count==0){ while(sta.size()!=0){ one.push_back(sta.top()); sta.pop(); } ret.push_back(one); one.clear(); level++; count=nextCount; nextCount=0; } } } return ret; }};
View Code

 

转载于:https://www.cnblogs.com/superzrx/p/3352995.html

你可能感兴趣的文章
爬虫学习笔记(一)初识爬虫
查看>>
生成随机数的模板
查看>>
SpringMVC文件上传
查看>>
hdu 2093
查看>>
进程描述符task_struct
查看>>
C++调用WCF
查看>>
Android 2D Graphics学习 Region和Canvas裁剪
查看>>
249. Group Shifted Strings
查看>>
如无必要,勿增实体 2012-03-08 17:17
查看>>
纸上谈兵: 树, 二叉树, 二叉搜索树[转]
查看>>
第一篇随笔
查看>>
Java中Date类型的工具类
查看>>
WebStorm快捷键收集
查看>>
testng,soket write error错误
查看>>
javaScript中string对象的方法
查看>>
跑一段代码遍历所有汉字
查看>>
生产者/消费者模式(二)
查看>>
Leetcode 226 Invert Binary Tree
查看>>
JAVA-初步认识-第十三章-多线程(卖票示例)
查看>>
[译]转译器: 今日大不同
查看>>