力扣103 二叉樹的鋸齒形遍歷

2021-10-09 06:07:17 字數 2336 閱讀 2236

題目描述

給定乙個二叉樹,返回其節點值的鋸齒形層次遍歷。(即先從左往右,再從右往左進行下一層遍歷,以此類推,層與層之間交替進行)。

分析思路

1.雙端佇列

def zigzaglevelorder(self, root: treenode) -> list[list[int]]:

if not root:

return

q=collections.deque()

mark=0

res=

while q:

level=

if mark%2==0:

for _ in range(len(q)):

node=q.popleft()

else:

for _ in range(len(q)):

node=q.pop()

mark+=1

return res

2.兩個棧實現

python:

def print( proot):

# write code here

res =

if proot == none:

return res

stack1 =

stack2 =

level =

while stack1 or stack2:

while stack1:

cur = stack1[-1]

if cur.left != none:

if cur.right != none:

stack1.pop()

if level:

level =

while stack2:

cur = stack2[-1]

if cur.right != none:

if cur.left != none:

stack2.pop()

if level:

level =

return res

c++

vector> print(treenode* proot) 

if(tmp.size())

while(!stack2.empty())

if(tmp.size())

}return res;

}

3.輸出結果

完整例子如下

def print(proot):

# write code here

res =

if proot == none:

return res

stack1 =

stack2 =

while stack1 or stack2:

while stack1:

cur = stack1[-1]

if cur.left != none:

if cur.right != none:

stack1.pop()

while stack2:

cur = stack2[-1]

if cur.right != none:

if cur.left != none:

stack2.pop()

return res

class treenode:

def __init__(self, x):

self.val = x

self.left = none

self.right = none

def main():

t1 = treenode(1)

t2 = treenode(2)

t3 = treenode(3)

t4 = treenode(4)

t5 = treenode(5)

t6 = treenode(6)

t7 = treenode(7)

t1.left = t2

t1.right = t3

t2.left = t4

t2.right = t5

t3.left = t6

t4.right = t7

print(print(t1))

if __name__ == "__main__":

main()

103 二叉樹的鋸齒形層次遍歷

本題跟102很像,就是將二叉樹的偶數層逆序輸出 我是直接將上一題的結果的偶數層reverse一下 definition for a binary tree node.class treenode def init self,x self.val x self.left none self.right...

103 二叉樹的鋸齒形層次遍歷

給定乙個二叉樹,返回其節點值的鋸齒形層次遍歷。即先從左往右,再從右往左進行下一層遍歷,以此類推,層與層之間交替進行 例如 給定二叉樹 3,9,20,null,null,15,7 3 9 20 15 7返回鋸齒形層次遍歷如下 3 20,9 15,7 看到本題目,首先想到的是使用佇列或棧,然而簡單使用這...

103 二叉樹的鋸齒形層次遍歷

難度 中等 題目描述 思路總結 層次遍歷 insert頭 題解一 definition for a binary tree node.class treenode def init self,x self.val x self.left none self.right none from colle...