算法练习之平衡二叉树
2棵二叉平衡树,找出值不相等的节点,打印节点坐标(位置信息)
0
/ \
3 5
/ \
7 10
2
/ \
6 9
/ \
7 8
思路:明显的递归遍历(深度遍历或广度遍历)这里就用比较简单的方法,深度遍历了。
思考了很久如何获取坐标位置,本来是用闭包来做,但是好像修改后获取到的坐标不准确了,改为参数传入了,一起递归。
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def test(self, tree1: TreeNode, tree2: TreeNode):
p = []
def search(tree1, tree2, x, y):
if not tree1 and not tree2:
return
if not tree1 or not tree2:
p.append((x, y))
return
print(x, y, tree1.val, tree2.val)
if tree1.val != tree2.val:
p.append((x, y))
search(tree1.left, tree2.left, x*2, y+1)
search(tree1.right, tree2.right, x*2+1, y+1)
search(tree1, tree2, 0, 0)
return p
if __name__ == "__main__":
sl = Solution()
t1 = TreeNode(0)
t1.left = TreeNode(4)
t1.right = TreeNode(5)
t1.left.left = TreeNode(6)
t1.left.right = TreeNode(7)
t2 = TreeNode(2)
t2.left = TreeNode(2)
t2.right = TreeNode(9)
r = sl.test(t1, t2)
print(r)
做完了发现其实很容易,但是做了一个小时诶,平时做得比较多的是动态规划类的题目,碰到树的题目还是有点害怕的,还是要多练习多练习