[leetCode By Python]100. Same Tree
2018-02-01 23:07
393 查看
题目:
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:
Example 2:
Example 3:
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(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def isSameTree(self, p, q): """ :type p: TreeNode :type q: TreeNode :rtype: bool """ if p==q==None: return True if p and q and p.val ==q.val: return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)#利用递归的方法 return False if __name__ == '__main__': l1_1 = TreeNode(1) l1_2 = TreeNode(2) l1_3 = TreeNode(3) l1_1.left = l1_2 l1_1.right = l1_3 l2_1 = TreeNode(1) l2_2 = TreeNode(2) l2_3 = TreeNode(3) l2_1.left = l2_2 l2_1.right = l2_3 l3 = Solution().isSameTree(l1_1,l2_1) print l3
相关文章推荐
- [LeetCode By Python]108. Convert Sorted Array to Binary Search Tree
- [leetCode By python]104. Maximum Depth of Binary Tree
- [leetCode By Python]110. Balanced Binary Tree
- [leetCode By Python]111. Minimum Depth of Binary Tree
- [Leetcode]@python 100. Same Tree
- [leetCode By Python]101. Symmetric Tree
- [leetcode] 100. Same Tree
- LeetCode 100. Same Tree
- [leetcode]Convert Sorted Array to Binary Search Tree @ Python
- [LeetCode By Python]122. Best Time to Buy and Sell Stock II
- [LeetCode By Python]26. Remove Duplicates from Sorted Array
- [LeetCode By python]35. Search Insert Position
- [LeetCode By Python]38. Count and Say
- [LeetCode BY Python]155. Min Stack
- [LeetCode] 100. Same Tree
- [LeetCode By Python] 2 Add Two Number
- [LeetCode By Python]172. Factorial Trailing Zeroes
- leetcode 100. Same Tree
- [leetcode] 100. Same Tree
- [leetcode: Python] 108. Convert Sorted Array to Binary Search Tree