Skip to content

二叉树第三十三道题目二叉树转化成累加树,python版本有误 #2908

Open
@xu2023-ICT

Description

@xu2023-ICT

其他语言版本中,python迭代版本2中,result完全没有必要

class Solution:
    def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if not root: return root
        stack = []
        result = []
        cur = root
        pre = 0
        while cur or stack:
            if cur:
                stack.append(cur)
                cur = cur.right
            else: 
                cur = stack.pop()
                cur.val+= pre
                pre = cur.val
                cur =cur.left
        return root

Activity

xu2023-ICT

xu2023-ICT commented on Mar 6, 2025

@xu2023-ICT
Author
class Solution:
    def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if not root:
            return None
        cur = root
        pre = 0
        stack = []
        # stack负责回溯,cur负责遍历 只有既没有回溯节点和遍历节点的时候,循环才会停止
        while stack or cur:
            if cur:
                stack.append(cur)
                cur = cur.right
            else:
                # 遇到空节点 回溯
                cur = stack.pop()
                cur.val += pre
                pre = cur.val
                cur = cur.left
        return root
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @xu2023-ICT

        Issue actions

          二叉树第三十三道题目二叉树转化成累加树,python版本有误 · Issue #2908 · youngyangyang04/leetcode-master