538. Convert BST to Greater Tree
Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.
Input: The root of a Binary Search Tree like this:
5
/ \
2 13
Output: The root of a Greater Tree like this:
18
/ \
20 13
solution:
- 先更新父节点,再更新左子树,右子树的做法。慢!
class Solution:
def convertBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
def tree_sum(root):
if not root:
return 0
return root.val + tree_sum(root.left) + tree_sum(root.right)
def f(node, accum):
if not node:
return None
right_sum = tree_sum(node.right)
node.val = node.val + accum + right_sum
if node.left:
f(node.left, node.val)
if node.right:
f(node.right, accum)
f(root, 0)
return root
- 递归地先计算右节点,父节点和左节点
class Solution:
def convertBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
self.curr_sum = 0 # 用于记录累加的值
return convert_help(root)
def convert_help(root):
if not root:
return
convert_help(root.right)
root.val = root.val + self.curr_sum
self.curr_sum = root.val
convert_help(root.left)
return root
100. Same Tree
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
Input: 1 1
/ \ / \
2 3 2 3
[1,2,3], [1,2,3]
Output: true
Input: 1 1
/ \
2 2
[1,2], [1,null,2]
Output: false
Input: 1 1
/ \ / \
2 1 1 2
[1,2,1], [1,1,2]
Output: false
solution:
class Solution:
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
if not q and not p:
return True
elif q and not p:
return False
elif not q and p:
return False
elif q.val == p.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right):
return True
else:
return False
class Solution:
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
if p and q:
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
return p is q
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。