当前位置:网站首页>【LeetCode】103. Zigzag sequence traversal of binary tree

【LeetCode】103. Zigzag sequence traversal of binary tree

2022-06-12 22:22:00 LawsonAbs

1. subject

2. thought

(1) Level traversal , You only need to output , Just adjust it ok. If you adjust it as you enter it , Will lead to changes in the whole sequence , Cause uncontrollable
(2) data structure queue Use .
For common data structures and functions , We should keep it in mind . For example, flip a list, have access to reversed Method , But it's not flipping in place .

3. Code

# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
import copy
from queue import Queue
class Solution:
    def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:        
        res = []
        if root is None:
            return res
        que = Queue() #  Define a queue 
        cnt = 0
        tmp = [root]        
        while(len(tmp)):            
            for i in range(len(tmp)):#  take temp Put the elements in one by one into que in  
                que.put(tmp[i])
            tmp.clear() 
            cur_res = [] #  Node value of current layer 
            while(que.qsize()): #  Judge que The content in  
                cur = que.get() #  Get the header element 
                # print(cur.val,hight)
                if cur.left is not None:
                    tmp.append(cur.left)
                if cur.right is not None:
                    tmp.append(cur.right)
                cur_res.append(cur.val) #  It's very strange why such an error is reported ?
            if cnt % 2==1:
                cur_res= list(reversed(cur_res))
            res.append(copy.deepcopy(cur_res))
            cnt+=1
        return res
原网站

版权声明
本文为[LawsonAbs]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206122217099512.html