A
A
Algorithm Practice
Search…
A
A
Algorithm Practice
Introduction
Lintcode
Leetcode
Math
Tree
94 Binary Tree Inorder Traversal
100 Same Tree
114 Flatten Binary Tree to Linked List
116 Populating Next Right Pointers in Each Node
117 Populating Next Right Pointers in Each Node II
124 Binary Tree Maximum Path Sum
144 Binary Tree Preorder Traversal
145 Binary Tree Postorder Traversal
366 Find Leaves of Binary Tree
257 Binary Tree Paths
235 Lowest Common Ancestor of a Binary Search Tree
236 Lowest Common Ancestor of a Binary Tree
671 Second Minimum Node In a Binary Tree
662 Maximum Width of Binary Tree
101 Symmetric Tree
102 Binary Tree Level Order Traversal
103 Binary Tree Zigzag Level Order Traversal
104 Maximum Depth of Binary Tree
107 Binary Tree Level Order Traversal II
108 Convert Sorted Array to Binary Search Tree
110 Balanced Binary Tree
111 Minimum Depth of Binary Tree
112 Path Sum
113 Path Sum II
623 Add One Row to Tree
222 Count Complete Tree Nodes
450 Delete Node in a BST
156 Binary Tree Upside Down
536 Construct Binary Tree from String
543 Diameter of Binary Tree
545 Boundary of Binary Tree
105 Construct Binary Tree from Preorder and Inorder Traversal
106 Construct Binary Tree from Inorder and Postorder Traversal
606 Construct String from Binary Tree
655 Print Binary Tree
742 Closest Leaf in a Binary Tree
783 Minimum Distance Between BST Nodes
Graph
Two Pointers
Linked List
Topological Sort
Hash Table
Trie
Sort
Binary Search
Heap
Breadth First Search
Stack
Backtracking
Dynamic Programming
Union Find
Scan Line
String
Reservoir Sampling
Recursion
Google
Powered By
GitBook
100 Same Tree
100. Same Tree
1. Question
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:
1
Input:
2
1 1
3
/ \ / \
4
2 3 2 3
5
6
[1,2,3], [1,2,3]
7
8
Output: true
Copied!
Example 2:
1
Input:
2
1 1
3
/ \
4
2 2
5
6
[1,2], [1,null,2]
7
8
9
Output: false
Copied!
Example 3:
1
Input:
2
1 1
3
/ \ / \
4
2 1 1 2
5
6
[1,2,1], [1,1,2]
7
8
9
Output: false
Copied!
2. Implementation
(1) Recursion
1
class
Solution
{
2
public
boolean
isSameTree
(
TreeNode
p
,
TreeNode
q
)
{
3
if
(
p
==
null
&&
q
==
null
)
return
true
;
4
if
(
p
==
null
||
q
==
null
||
p
.
val
!=
q
.
val
)
return
false
;
5
return
isSameTree
(
p
.
left
,
q
.
left
)
&&
isSameTree
(
p
.
right
,
q
.
right
);
6
}
7
}
Copied!
3. Time & Space Complexity
Recursion: 时间复杂度: O(m + n), 空间复杂度O(h1 + h2), h1和h2分别两颗树的高度
Previous
94 Binary Tree Inorder Traversal
Next
114 Flatten Binary Tree to Linked List
Last modified
2yr ago
Copy link
Contents
100. Same Tree
1. Question
2. Implementation
3. Time & Space Complexity