Binary Tree Inorder Traversal – 查询

huangapple go评论68阅读模式
英文:

Binary Tree Inorder Traversal - query

问题

I am looking at LeetCode problem 94. Binary Tree Inorder Traversal:

给定二叉树的根节点 root,返回其节点值的中序遍历

For the above problem I tried the following code:

对于上述问题,我尝试了以下代码:

class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        list1 = []
        if root == None:
            return None
            inorderTraversal(root.left)
            list1.append(root.val)
            inorderTraversal(root.right)
        print(list1)
        return list1

But it fails the most simple test cases, and gives errors.

但它在最简单的测试案例中失败并产生错误。

I found a working solution:

我找到了一个可行的解决方案:

class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        list1 = []
        if root == None:
            return None
        def create_list(root, list1):
            if root == None:
                return
            create_list(root.left, list1)
            list1.append(root.val)
            create_list(root.right, list1)
        create_list(root, list1)
        print(list1)
        return list1

What is wrong with my code?

我的代码有什么问题?

I would like to better understand how recursion works for Binary Trees. I can solve basic problems, but as the problem statement gets tougher, it gets hard to imagine/dry run what recursion would return.

我想更好地理解递归在二叉树中的工作原理。我可以解决基本问题,但随着问题描述变得更复杂,很难想象/模拟递归会返回什么。

英文:

I am looking at LeetCode problem 94. Binary Tree Inorder Traversal:

> Given the root of a binary tree, return the inorder traversal of its nodes' values.

For the above problem I tried the following code:

class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        list1=[]
        if root==None:
            return None
            inorderTraversal(root.left)
            list1.append(root.val)
            inorderTraversal(root.right)
        print(list1)
        return list1

But it fails the most simple test cases, and gives errors.

I found a working solution:

class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        list1=[]
        if root==None:
            return None
        def create_list(root,list1):
            if root==None:
                return
            create_list(root.left,list1)
            list1.append(root.val)
            create_list(root.right,list1)
        create_list(root,list1)
        print(list1)
        return list1

What is wrong with my code?

I would like to better understand how recursion works for Binary Trees. I can solve basic problems, but as the problem statement gets tougher, it gets hard to imagine/dry run what recursion would return.

答案1

得分: 0

这些是有问题的代码部分:

  • inorderTraversal 不是一个已知的函数。应该是 self.inorderTraversal,这样你才能访问到方法

  • 你有一些无效代码,因为在 return None 后面的语句永远不会执行。相关的语句不应该是 if 块的一部分,并且缩进要少一些。

  • self.inorderTraversal 不应该返回 None。如果树是空的,你应该返回一个空列表,而不是 None

  • self.inorderTraversal 返回一个列表,但是你忽略了从递归调用中返回的列表。这意味着你丢失了信息,这些递归调用白白做了所有的工作。相反,应该从这些递归调用返回的列表构建当前列表。

如果修复了这些问题,代码应该如下所示:

class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        list1 = []
        if root is None:
            return []
        list1 = self.inorderTraversal(root.left)
        list1.append(root.val)
        list1.extend(self.inorderTraversal(root.right))
        return list1

然而,这种解决方法不够内存高效,因为它不断地从现有列表中创建新列表。一个更符合 Python 风格的方法是创建一个生成器函数,并将生成的值收集到一个列表中:

class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        def iterate(node):
            if node:
                yield from iterate(node.left)
                yield node.val
                yield from iterate(node.right)
        
        return list(iterate(root))
英文:

These are the issues with the non-working code:

  • inorderTraversal is not a known function. It should be self.inorderTraversal so you access the method.

  • You have some dead code, as the statements after return None will never execute. The concerned statements should not be part of the if block and have less indentation

  • self.inorderTraversal should not return None. If the tree is empty, you should return an empty list, not None.

  • self.inorderTraversal returns a list, but you ignore the lists that are returned from the recursive calls. That means you lose information and those recursive calls do all their work for nothing. Instead, build the current list from those lists coming back from recursion.

Here is what the code would look like if those issues are corrected:

class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        list1 = []
        if root is None:
            return []
        list1 = self.inorderTraversal(root.left)
        list1.append(root.val)
        list1.extend(self.inorderTraversal(root.right))
        return list1

This solution is however not memory efficient, as it keeps creating new lists from existing lists. A more pythonic way would be to create a generator function and collect the yielded values into one list:

class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        def iterate(node):
            if node:
                yield from iterate(node.left)
                yield node.val
                yield from iterate(node.right)
        
        return list(iterate(root))

答案2

得分: -1

Sure, here is the translation of the code part you provided:

class Solution:
    def inorderPrint(self, node, res):
        if node == None:
            return res
        self.inorderPrint(node.left, res)
        res.append(node.val)
        self.inorderPrint(node.right, res)
        
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        res = []
        self.inorderPrint(root, res)
        return res

Please note that I've only translated the code portion and removed the non-code content.

英文:

Steps for inorder traversal of a binary tree:

  1. First traverse till last node in left branch of every next node.
  2. Return when None node found
  3. Append current element to in order list
  4. At this point this means we traversed all left possible nodes.
  5. Now go to right branch and do the same.
  6. Print the inorder list.

Time complexity: O(N)
Space complexity: O(N)

class Solution:
    def inorderPrint(self, node, res):
        if node==None:
            return res
        self.inorderPrint(node.left,res)
        res.append(node.val)
        self.inorderPrint(node.right,res)
        
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        res = []
        self.inorderPrint(root,res)
        return res

huangapple
  • 本文由 发表于 2023年5月7日 19:55:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76193769.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定