Open azl397985856 opened 3 years ago
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} p
* @param {TreeNode} q
* @return {boolean}
*/
var isSameTree = function(p, q) {
if(p === null && q === null) return true;
if(p === null || q === null) return false;
if (p.val !== q.val) return false;
return isSameTree(p.left, q.left) &&
isSameTree(p.right, q.right)
};
C++ Code:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if (p == nullptr || q == nullptr) {
return p == nullptr && q == nullptr;
}
if (p->val != q->val) {
return false;
}
return (isSameTree(p->left, q->left) && isSameTree(p->right, q->right));
}
};
令 n 为树的节点个数。
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null || q == null) return p == q;
return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}
Time Complexity: O(n) Space Complexity: O(h)
递归。分其中情况讨论,两者均为空,两者只有一个为空,两者均有值但值不同,两者值相同。在值相同时用递归进行下一步判断,到空值出现时停止递归。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
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
elif p.val!=q.val:
return False
else:
return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
时间复杂度:O(m) ,递归过程遍历节点进行判断,m为两树中节点数较少数的节点数。
空间复杂度:O(m) ,递归过程遍历结点,每次递归空间复杂度为常数
Compare the two nodes (if exists) at the same position from the two trees recursively.
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
def dfs(n1, n2):
if not n1 and not n2: return True
if not n1 or not n2: return False
if n1.val != n2.val: return False
return dfs(n1.left, n2.left) and dfs(n1.right, n2.right)
return dfs(p, q)
p
and q
are null
, return true
.null
or their values are not equal, return false
.class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
} else if (p == null || q == null || p.val != q.val) {
return false;
}
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}
Time: O(n)
Space: O(h) = O(n)
可以直接递归来做,也可以用前序遍历 + 中序遍历来做, 同时知道了前序遍历和中序遍历结果, 那么这棵树就是唯一确定的了。
如果两棵树都为空,则两棵树相同;
如果一棵树为空,一棵树不为空,则两棵树一定不同;
如果两棵树都不为空,即结构相同,则判断它们的值是否相等
如果值不相等,则不相同
如果值相等,则分别递归判断左右子树是否相同
实现语言: C++
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
bool res;
if(p == NULL && q == NULL) return true;
if(p != NULL && q == NULL) return false;
else if(p == NULL && q != NULL) return false;
else if(p->val != q->val) return false;
return(isSameTree(p->left, q->left) && isSameTree(p->right, q->right)); /* 递归地进行比较 */
}
};
同时知道了前序遍历和中序遍历结果, 那么这棵树就是唯一确定的了。同理, 如果两棵树的前序遍历完全一样,中序遍历完全一样,那么这棵树就是相同的树。
实现语言: C++
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(p == NULL && q == NULL) return true;
if(p != NULL && q == NULL) return false;
else if(p == NULL && q != NULL) return false;
else if(p->val != q->val) return false;
return(preOrder(p) == preOrder(q) && inOrder(p) == inOrder(q));
}
string preOrder(TreeNode* root) /* 根左右 */
{
string res;
if(root == NULL) // 空节点占位
{
res.push_back('#');
return res;
}
res.push_back(root->val);
string left = preOrder(root -> left);
string right = preOrder(root -> right);
res.insert(res.end(), left.begin(), left.end());
res.insert(res.end(), right.begin(), right.end());
return res;
}
string inOrder(TreeNode* root) /* 左根右 */
{
string res;
if(root == NULL) // 空节点占位
{
res.push_back('#');
return res;
}
res = inOrder(root -> left);
res.push_back(root->val);
string right = inOrder(root -> right);
res.insert(res.begin(), right.begin(), right.end());
return res;
}
};
递归
var isSameTree = function (p, q) {
if (!p || !q) {
return !p && !q
}
return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
};
递归,当p和q都为空时为true,当p或者q其中一个为空时为false,当p.val和q.val不相等时为false 确保p和q的左右子树都为true时,p和q才为相同的两颗树
Java Code:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p==null&&q==null)
{
return true;
}
if(p==null || q==null)
{
return false;
}
if(p.val!=q.val)
{
return false;
}
return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
}
}
复杂度分析
思路:递归
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p == null && q == null){
return true;
}
//节点都为空时相同
else if(p == null || q == null){
return false;
}
//只有一个为空必不相同
else if(p.val != q.val){
return false;
}
else{
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
//递归,继续判断结点的左右子节点
}
}
时间复杂度:O(N) 空间复杂度:O(N)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
bool ans1, ans2;
if (p == nullptr || q == nullptr) {
return p == q;
}
if (p->val != q->val) {
return false;
}
ans1 = isSameTree(p->left, q->left);
ans2 = isSameTree(p->right, q->right);
return ans1 && ans2;
}
};
有一点tricky
Recursion, postorder.
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) return true;
if (p == null || q == null) return false;
if (p.val != q.val) return false;
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}
Time = O(n).
Space = O(n).
递归
func isSameTree(p *TreeNode, q *TreeNode) bool {
if p == nil && q==nil{
return true
}else if p == nil || q==nil{
return false
}else if p.Val !=q.Val{
return false
}else{
return isSameTree(p.Left,q.Left)&&isSameTree(p.Right,q.Right)
}
}
复杂度分析
Idea: recursion
class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
if p and q:
return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right) and (p.val == q.val)
else:
return p == q
Time O(N)
深度优先遍历。
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
if not p and not q:
return True
if not p or not q:
return False
if p.val != q.val:
return False
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
遍历整棵树
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
flag=True
if p and q:
if p.val != q.val:
flag=False
else:
return self.isSameTree(q.left,p.left) and self.isSameTree(q.right,p.right)
if p and not q:
flag=False
if not p and q:
flag=False
return flag
时间复杂度:O(N)
空间复杂度:O(N)
递归三部曲
class Solution {
public:
//递归三部曲
//1.首先要确定递归函数和返回值
//比较两个树,可直接返回bool
//2.递归终止条件
//(1)两个节点都为NULL,返回true
//(2)一个为空,一个有值,返回false;
//(3)两个都有值,但不等,返回false;
//(4)两个都有值,相等,返回true
//3.确定递归函数
bool isSameTree(TreeNode* p, TreeNode* q) {
return compare(p, q);
}
bool compare(TreeNode* p, TreeNode* q) {
if (p == nullptr && q == nullptr) return true;
else if (p != nullptr && q == nullptr) return false;
else if (p == nullptr && q != nullptr) return false;
else if (p->val != q->val) return false;
return compare(p->left, q->left) && compare(p->right, q->right);
}
};
迭代(队列)
class Solution {
public:
//迭代,利用队列
bool isSameTree(TreeNode* p, TreeNode* q) {
if (p == nullptr && q == nullptr) return true;
if (p == nullptr || q == nullptr) return false;
queue<TreeNode*> que;
que.push(p);
que.push(q);
while (!que.empty()) {
TreeNode* leftNode = que.front();
que.pop();
TreeNode* rightNode = que.front();
que.pop();
if (!leftNode && !rightNode) continue;
if (!leftNode || !rightNode || leftNode->val != rightNode->val) return false;
que.push(leftNode->left);
que.push(rightNode->lef);
que.push(leftNode->right);
que.push(rightNode->righ);
}
return true;
}
};
时间复杂度为O(n)
Algo
- Judgement must be paried
- recur
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
# depth == 1, strick
if not p and not q: return True
if not p or not q: return False
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
递归DFS
JavaScript Code
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} p
* @param {TreeNode} q
* @return {boolean}
*/
var isSameTree = function(p, q) {
if (p === null && q === null) return true;
if (p === null || q === null) return false;
return p.val === q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
};
时间复杂度:O(N)
空间复杂度:O(Height)
思路: 1)先比较结点p, q 2)再递归比较对应的左右结点
'''python
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
if not p or not q:
return p==q
else:
if p.val == q.val:
return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
'''
class Solution {
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;
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}
前序遍历以及中序遍历整个tree,如果都相同则两个tree一样
class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
self.pNodes = []
self.qNodes = []
self.pre_transversal(self.pNodes, p)
self.pre_transversal(self.qNodes, q)
if self.pNodes != self.qNodes:
return False
self.pNodes = []
self.qNodes = []
self.in_transversal(self.pNodes, p)
self.in_transversal(self.qNodes, q)
return True if self.pNodes == self.qNodes else False
def pre_transversal(self, queue: List, node: Optional[TreeNode]):
if not node:
queue.append(None)
return
queue.append(node.val)
self.pre_transversal(queue, node.left)
self.pre_transversal(queue, node.right)
def in_transversal(self, queue: List, node: Optional[TreeNode]):
if not node:
queue.append(None)
return
self.in_transversal(queue, node.left)
queue.append(node.val)
self.in_transversal(queue, node.right)
时间复杂度 :O(n)
空间复杂度:O(h)
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
}
if (p == null || q == null) {
return false;
}
if (p.val != q.val) {
return false;
}
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
C++ Code:
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(p==NULL && q==NULL)
return true;
if( (p==NULL&&q) || (p && q==NULL))
return false;
if(p->val != q->val)
return false;
if(isSameTree(p->left, q->left)==false)
return false;
if(isSameTree(p->right, q->right)==false)
return false;
return true;
}
};
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(p==NULL && q==NULL)
return true;
if((p==NULL && q) || (p && q==NULL) )
return false;
vector<TreeNode*> pStack;
vector<TreeNode*> qStack;
pStack.push_back(p);
qStack.push_back(q);
while(pStack.size() && qStack.size())
{
TreeNode* pTop = pStack.back();
TreeNode* qTop = qStack.back();
if(pTop->val != qTop->val)
return false;
pStack.pop_back();
qStack.pop_back();
if( (pTop->left==NULL && qTop->left) || (pTop->left && qTop->left==NULL) )
return false;
else if(pTop->left && qTop->left)
{
pStack.push_back(pTop->left);
qStack.push_back(qTop->left);
}
if( (pTop->right==NULL && qTop->right) || (pTop->right && qTop->right==NULL) )
return false;
else if(pTop->right && qTop->right)
{
pStack.push_back(pTop->right);
qStack.push_back(qTop->right);
}
}
return true;
}
};
拿到题的直觉解法
递归
AC
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
return preorder(p, q);
}
public boolean preorder(TreeNode p, TreeNode q) {
if(p == null && q == null) return true;
if(p == null || q == null) return false;
return p.val == q.val && preorder(p.left, q.left) && preorder(p.right, q.right);
}
}
dfs time: 最坏情况,每个node都比较到了,因此O(N) space: 维护递归stack的空间,由递归的层数决定,因此为O(logN);
递归求解,同时遍历两个树,判断是否相同
if p.val==q.val:
return f(p.left,q.left) and f(p.right,q.right)
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
def traversal(p: TreeNode, q: TreeNode):
if p is None or q is None:
if p is None and q is None:
return True
else:
return False
if p.val == q.val:
return traversal(p.left, q.left) and traversal(p.right, q.right)
else:
return False
return traversal(p, q)
# pre-order traversal
# for each node: check if curr node has same value
# recursively check both left and right child
# time: O(N)
# space: O(H)
class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
if not p and not q:
return True
if not p or not q:
return False
if p.val != q.val:
return False
leftSame = self.isSameTree(p.left, q.left)
rightSame = self.isSameTree(p.right, q.right)
return leftSame and rightSame
//use recursion to check every node is exactly the same, pre order traverse, compare the node at the exact same place
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) return true;
if (p == null || q == null || p.val != q.val) return false;
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
思路:
复杂度分析:
代码(C++):
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
1. 递归法:
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if (p && q)
return (p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right));
else if (!p && !q)
return true;
return false;
}
};
Simply do a pre-order traversal, and compare the nodes
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if (!p && !q)
return true;
if ((!p && q) || (p && !q) || (p->val != q->val))
return false;
return isSameTree(p->left, q->left) & isSameTree (p->right, q->right);
}
};
O(n): we need to visit each node at least once
O(h): h is the height of the tree. worst case could be O(n)
//Recursion
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) return true;
if (p == null || q == null) return false;
if (p.val != q.val) return false;
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}
//Iteration
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
Queue<TreeNode> queue = new LinkedList<>();
if (p == null && q == null) return true;
if (p == null || q == null) return false;
queue.offer(p);
queue.offer(q);
while (!queue.isEmpty()) {
TreeNode first = queue.poll();
TreeNode second = queue.poll();
if (first == null && second == null) continue;
if (first == null || second == null) return false;
if (first.val != second.val) return false;
queue.offer(first.left);
queue.offer(second.left);
queue.offer(first.right);
queue.offer(second.right);
}
return true;
}
}
https://leetcode-cn.com/problems/same-tree/
前序, 先对比root节点的值,一样的话对比左右子树
https://leetcode-cn.com/problems/same-tree/
O(n)
O(n)
https://leetcode-cn.com/problems/same-tree/
前序, 先对比root节点的值,一样的话对比左右子树
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p == null && q == null) return true;
if(p == null || q == null) return false;
if(p.val != q.val) return false;
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}
O(n)
O(n)
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
if not p and not q:
return True
elif not p and q:
return False
elif not q and p:
return False
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
time: O(N) space: O(N)
https://leetcode.com/problems/same-tree/
recursion
function isSameTree(p, q) {
if (!p && !q) return true;
if (!p || !q || p.val !== q.val) return false;
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
空间与时间 O(n)
dfs
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null || q == null) return p == q;
if (p.val != q.val) return false;
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
if not p and not q:
return True
elif p and q:
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
else:
return False
Explanation
Python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
# Approach 1
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
if not p and not q:
return True
if not p or not q:
return False
if p.val != q.val:
return False
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
# Approach 2
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
def isSameNode(a, b):
if not a and not b:
return True
if not a or not b:
return False
return a.val == b.val
queue = [(p,q)]
while queue:
p, q = queue.pop(0)
if not isSameNode(p,q):
return False
if p:
queue.append((p.left, q.left))
queue.append((p.right, q.right))
return True
Complexity
O(N)
O(N)
in the worst case and O(logN)
in the best case思路:先check 两棵树的当前节点值是否相等 然后迭代比较两个节点的左节点和右节点值是否相等。
Python 3 code:
class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
if not p and not q: return True
if p and not q: return False
if not p and q: return False
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
Time complexity: O(n) Space Complexity: O(logn)
I used BFS yesterday, so, for today, I am using Recursion. While searching the children for a parent of two trees, I directly compared the node value; if they were equal, continue to the farthest leave node, if they were not equal, return False directly.
使用语言:Python3
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
if not q and not p:
return True
if (q and not p) or (not q and p):
return False
if q.val != p.val:
return False
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
复杂度分析 时间复杂度:O(n) 空间复杂度:O(n)
https://leetcode.com/problems/same-tree/submissions/
Medium
Use both PreOrder and InOrder traversal of the trees.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
def preOrder(a, b):
if not a and not b:
return True
if (not a and b) or (a and not b) or (a.val != b.val):
return False
left = preOrder(a.left, b.left)
right = preOrder(a.right, b.right)
return left and right
def inOrder(a, b):
if not a and not b:
return True
if (not a and b) or (a and not b):
return False
left = inOrder(a.left, b.left)
if a.val != b.val or not left:
return False
right = inOrder(a.left, b.left)
if not right:
return False
return True
return preOrder(p, q) and inOrder(p, q)
时间复杂度:O(N) 空间复杂度:O(logN)
递归
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
if not p:
return not q
if not q:
return not p
if p.val != q.val:
return False
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
T: O(N) S: O(logN)
idea: recursion. if p.val==q.val, keep checking their children. Time: O(n) Space: O(h)
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p==null && q== null)
return true;
if(p==null || q==null)
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){
return true;
}
if(!p || !q || p.val !== q.val){
return false;
}
return isSameTree(p.left,q.left) && isSameTree(p.right,q.right)
};
// time O(n)
//space O(h)
DFS
C++ Code:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if (p == q) return true;
if ((!p || !q) || p->val != q->val) return false;
return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
};
复杂度分析
如果根节点都为空,则相同; 如果只有一个根节点为空,则不同; 根节点都不为空的情况,则当节点的值相同,并且左右子树都相同的情况下两树相同,否则不同。
/**
* @param {TreeNode} p
* @param {TreeNode} q
* @return {boolean}
*/
var isSameTree = function(p, q) {
if (!p && !q) {
return true;
} else if (!p || !q) {
return false;
} else {
return p.val === q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
};
标准dfs,就是看当前节点是不是一样,左子树是不是一样,右子树是不是一样
class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
def dfs(root1, root2):
if not root1 and not root2:
return True
if root1 and root2:
return (
root1.val == root2.val
and dfs(root1.left, root2.left)
and dfs(root1.right, root2.right)
)
return False
return dfs(p, q)
time complexity O(n)
space complexity O(h) h为 树的高度
TC: O(n) n = min(len(p), len(q)) SC: O(h) h = min(h(p), h(q))
class Solution(object):
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
if not q and not p:
return True
if q and p and p.val!=q.val:
return False
if (q and not p) or (p and not q) :
return False
return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
Ideas DFS 挖个坑,周末学习队列和BFS的解法 comment Runtime: 24 ms, faster than 96.22%
python代码
class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
if not p and not q:
return True
elif not p or not q:
return False
elif p.val != q.val:
return False
return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
复杂度分析
Recursion
class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
if not p and not q:
return True
if not p or not q:
return False
if p.val != q.val:
return False
return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
Iteration
class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
stack=[(p,q)]
while stack:
q,p = stack.pop()
if not q and not p:
continue
elif not q or not p or p.val != q.val:
return False
stack.extend(([p.left,q.left],[p.right,q.right]))
return True
Time: O(n)
Space: O(n)
100. 相同的树
入选理由
暂无
题目地址
https://leetcode-cn.com/problems/same-tree/
前置知识
题目描述
如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。
示例 1:
输入: 1 1 / \ / \ 2 3 2 3
输出: true 示例 2:
输入: 1 1 / \ 2 2
输出: false 示例 3:
输入: 1 1 / \ / \ 2 1 1 2
输出: false