Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

leetcode-thinkings-tree.md BFS 模版调整 #595

Open
likenow opened this issue Nov 10, 2023 · 3 comments
Open

leetcode-thinkings-tree.md BFS 模版调整 #595

likenow opened this issue Nov 10, 2023 · 3 comments
Labels
Daily Question 每日一题

Comments

@likenow
Copy link

likenow commented Nov 10, 2023

class Solution:
    def bfs(k):
        # 使用双端队列,而不是数组。因为数组从头部删除元素的时间复杂度为 N,双端队列的底层实现其实是链表。
        queue = collections.deque([root])
        # 记录层数
        steps = 0
        # 需要返回的节点
        ans = []
        # 队列不空,生命不止!
        while queue:
            size = len(queue)
            # 遍历当前层的所有节点
            for _ in range(size):
                node = queue.popleft()
                if (step == k) ans.append(node)
                if node.right:
                    queue.append(node.right)
                if node.left:
                    queue.append(node.left)
            # 遍历完当前层所有的节点后 steps + 1
            steps += 1
        return ans

上述模版,入队的顺序调整为:


class Solution:
    def bfs(k):
       ...
            for _ in range(size):
                ...

                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
                
            # 遍历完当前层所有的节点后 steps + 1
            steps += 1
        return ans

@likenow likenow added the Daily Question 每日一题 label Nov 10, 2023
@lording
Copy link

lording commented Nov 10, 2023 via email

@likenow
Copy link
Author

likenow commented Nov 10, 2023

您好,您的来信已收到,我会尽快给您回复的!

sorry, submitted to a wrong issues category.

@azl397985856
Copy link
Owner

bfs 不同于 dfs, dfs 会区分先序,中序和后序,因此 bfs 在这里 left 和 right 的顺序没有大的影响。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Daily Question 每日一题
Projects
None yet
Development

No branches or pull requests

3 participants