LeetCode 538 python 把二叉搜尋樹轉換為累加樹
阿新 • • 發佈:2019-01-11
思路:root.val += root.right root.left += root.val
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class solution: def __init__(self): self.sum = 0 def convertBST(self, root): if not root: return None self.convertBST(root.right) self.sum += root.val root.val = self.sum self.convertBST(root.left) return root
右孩子加到root.val上給root.val
root.val加到左孩子給左孩子
用self.sum存放當前遍歷過的節點值之和