-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsame-tree.js
71 lines (65 loc) · 1.68 KB
/
same-tree.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* Source: https://leetcode.com/problems/same-tree/
* Tags: [Tree,Depth-first Search]
* Level: Easy
* Updated: 2015-04-24
* Title: Same Tree
* Auther: @imcoddy
* Content: Given two binary trees, write a function to check if they are equal or not.
*
*
* Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
*/
/**
* Definition for binary tree
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} p
* @param {TreeNode} q
* @returns {boolean}
*/
/**
* Memo: compare root and children recursively.
* Complex: O(nlgn)
* Runtime: ms
* Tests: 54 test cases passed
* Rank: S
*/
var isSameTree = function(p, q) {
if ((!p && q) || (p && !q)) return false; // one is null
if (!p && !q) return true; // cautious both null nodes generates true
if (p.val !== q.val) return false; // val not equal
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); // check children
};
/**
* Memo: Check node recursively
* Complex: O(n)
* Runtime: 120ms
* Tests: 54 test cases passed
* Rank: S
* Updated: 2015-10-05
*/
function isSameTree(p, q) {
if (!p && !q) return true;
if (!p || !q) return false;
if (p.val !== q.val) return false;
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
var isSameTree = function(p, q) {
if ((p && !q) || (!p && q)) {
return false;
}
if (!p && !q) {
return true;
}
if (p.val !== q.val) {
return false;
} else {
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
};
console.log(isSameTree(null, null));