二叉樹的鋸齒形層次遍歷

2021-09-05 15:20:53 字數 1937 閱讀 8251

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

例如:給定二叉樹[3,9,20,null,null,15,7],

3

/ \9 20

/ \

15 7

返回鋸齒形層次遍歷如下:

[

[3],

[20,9],

[15,7]

]

解題思路:鋸齒形層次遍歷,又不單單是層次遍歷,一次從左到右,一次從右向左。

先看一下二叉樹的層次遍歷(即逐層地從左向右訪問所有節點),給定的二叉樹的層次遍歷結果為:

[

[3],

[9,20],

[15,7]

]

# definition for a binary tree node.

# class treenode:

# def __init__(self, x):

# self.val = x

# self.left = none

# self.right = none

class solution:

def levelorder(self, root):

""":type root: treenode

:rtype: list[list[int]]

"""if root is none:

return

cur=[root]

results=

while cur:

temp=

val=

for i in cur:

if i.left is not none:

if i.right is not none:

val+=[i.val]#val陣列存放每層的元素

cur=temp

return results

如何改進**,使一層從左到右遍歷,一層從右往左遍歷,交替進行:

考慮記錄樹的深度,當深度為偶數時,存放每層元素的陣列逆序;當深度為奇數時,存放每層元素的陣列正序;

# definition for a binary tree node.

# class treenode:

# def __init__(self, x):

# self.val = x

# self.left = none

# self.right = none

class solution:

def zigzaglevelorder(self, root):

""":type root: treenode

:rtype: list[list[int]]

"""if root is none:

return

cur=[root]

results=

length=0

while cur:

temp=

val=

for i in cur:

if i.left is not none:

if i.right is not none:

val+=[i.val]

length+=1

cur=temp

if(length%2!=0):

else:

return results

二叉樹的鋸齒形層次遍歷

給定乙個二叉樹,返回其節點值的鋸齒形層次遍歷。即先從左往右,再從右往左進行下一層遍歷,以此類推,層與層之間交替進行 例如 給定二叉樹 3,9,20,null,null,15,7 3 9 20 15 7 複製 返回鋸齒形層次遍歷如下 3 20,9 15,7 複製 definition for a bi...

二叉樹的鋸齒形層次遍歷

給定乙個二叉樹,返回其節點值的鋸齒形層次遍歷。即先從左往右,再從右往左進行下一層遍歷,以此類推,層與層之間交替進行 例如 給定二叉樹 3,9,20,null,null,15,7 3 9 20 15 7返回鋸齒形層次遍歷如下 3 20,9 15,7 分析 鋸齒型的意思就是,第一層順序,第二層逆序,第三...

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

給出一棵二叉樹,返回其節點值的鋸齒形層次遍歷 先從左往右,下一層再從右往左,層與層之間交替進行 您在真實的面試中是否遇到過這個題?yes 樣例給出一棵二叉樹,3 9 20 15 7返回其鋸齒形的層次遍歷為 3 20,9 15,7 definition of treenode public class...