algorithm notes: leetcode#100 same tree

Problem


Solution


Initial thoughts

Python implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class :
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
if p is None and q is None:
return True
if (p is None and q is not None) or (p is not None and q is None):
return False
if p.val != q.val:
return False
if self.isSameTree(p.left, q.left):
return self.isSameTree(p.right, q.right)
return False

Java implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p==null && q==null){ return true; }
if((p==null && q!=null) || (p!=null && q==null)){ return false; }
if(p.val != q.val){ return false; }
if(isSameTree(p.left, q.left)){ return isSameTree(p.right, q.right); }
return false;
}
}

Time complexity

O(n).

Space complexity

O(1).


100. Same Tree
(中文版) 算法笔记: 力扣#100 相同的树