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

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

Open
xu2023-ICT opened this issue Mar 6, 2025 · 1 comment

Comments

@xu2023-ICT
Copy link

其他语言版本中,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
@xu2023-ICT
Copy link
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
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant