题目 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.
Example 1:
Input: 1 1
/ \ / \
2 3 2 3
[1,2,3], [1,2,3]
Output: true
Example 2:
Input: 1 1
/ \
2 2
[1,2], [1,null,2]
Output: false
Example 3:
Input: 1 1
/ \ / \
2 1 1 2
[1,2,1], [1,1,2]
Output: false
思路
递归
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
if p == None and q == None:
return True
elif p == None or q == None:
return False
if p.val != q.val:
return False
if self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right):
return True
else:
return False
题目 101. Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3]
is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3]
is not:
1
/ \
2 2
\ \
3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
思路
思路一:用递归的方法很简单:
def sub(self,p,q):
if p == None and q == None:
return True
elif p == None or q == None:
return False
if p.val != q.val:
return False
if self.sub(p.left,q.right) and self.sub(p.right,q.left):
return True
else:
return False
def isSymmetric(self, root: TreeNode) -> bool:
if root == None:
return True
else:
return self.sub(root.left,root.right)
思路二:用栈的方法:按照 left - right - root的顺序 把整个左子树的值压入栈中,然后 按照 right - left - root的顺序遍历右子树。
def isSymmetric(self, root: TreeNode) -> bool:
if root == None:
return True
l_root = root.left
r_root = root.right
if l_root == None and r_root == None:
return True
elif l_root == None or r_root == None:
return False
stack_root = []
nums = []
while(1):
while(1):
while(l_root.left):
stack_root.append(l_root)
l_root = l_root.left
nums.append(l_root.val)
if(l_root.right):
stack_root.append(l_root)
l_root = l_root.right
else:
break
if len(stack_root)>0:
while l_root.right == None and len(stack_root)>0:
l_root = stack_root.pop()
nums.append(l_root.val)
if l_root.right:
l_root = l_root.right
else:
break
else:
break
print(nums)
nums1 = []
while(1):
while(1):
while(r_root.right):
stack_root.append(r_root)
r_root = r_root.right
nums1.append(r_root.val)
if len(nums)>0:
if r_root.val != nums[0]:
return False
else:
nums = nums[1:]
else:
return False
if(r_root.left):
stack_root.append(r_root)
r_root = r_root.left
else:
break
if len(stack_root)>0:
while r_root.left == None and len(stack_root)>0:
r_root = stack_root.pop()
nums1.append(r_root.val)
if len(nums)>0:
if r_root.val != nums[0]:
return False
else:
nums = nums[1:]
else:
return False
if r_root.left:
r_root = r_root.left
else:
break
else:
break
return True
但是用栈,由于遍历完左侧的树才去遍历右侧的树,因此比较慢