0
点赞
收藏
分享

微信扫一扫

5.1.8判断相同树


文章目录

  • ​​1.题目​​
  • ​​2.代码​​

1.题目

  • ​​题目要求​​
  • 思路:判断两棵树是否相同和之前的判断两棵树是否对称都是一样的原理,利用深度优先搜索 DFS 来递归
  • eg:

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

2.代码

递归版本
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);
}
};


前序迭代版,用stack
class Solution{
public:
bool isSameTree(TreeNode* p, TreeNode* q)
{
stack<TreeNode*> st;
st.push(p);
st.push(q);
while (!st.empty())
{
TreeNode* tmp_q=st.top();st.pop();
TreeNode* tmp_p=st.top();st.pop();
if (!tmp_q && !tmp_p) continue;
if ((tmp_q && !tmp_p) || (!tmp_q && tmp_p) || (tmp_q->val != tmp_p->val)) return false;

st.push(tmp_p->right);
st.push(tmp_q->right);

st.push(tmp_p->left);
st.push(tmp_q->left);
}
return true;
}
};



中序迭代版,用stack
class Solution{
public:
bool isSameTree(TreeNode* p, TreeNode* q)
{
stack<TreeNode*> st;
TreeNode* tmp_p=p;
TreeNode* tmp_q=q;
while (tmp_p || tmp_q || !st.empty())
{
while (tmp_p || tmp_q)
{
st.push(tmp_p);
st.push(tmp_q);
tmp_p=tmp_p->left;
tmp_q=tmp_q->left;
}
TreeNode* tmp_q = st.top();st.pop();
TreeNode* tmp_p = st.top();st.pop();
if (!tmp_q && !tmp_p) continue;
if ((tmp_q && !tmp_p) || (!tmp_q && tmp_p) || (tmp_q->val != tmp_p->val)) return false;
tmp_q=tmp_q->right;
tmp_p=tmp_p->right;
}

return true;
}


后序遍历的方法后面在看



层序迭代版,对于层序遍历的迭代写法,其实跟先序遍历的迭代写法非常的类似,只不过把栈换成了队列
class Solution{
public:
bool isSameTree(TreeNode* p, TreeNode* q)
{
queue< TreeNode*> dq;
dq.push(p);
dq.push(q);
while (!dq.empty())
{
TreeNode* tmp_p=dq.front();dq.pop();
TreeNode* tmp_q=dq.front();dq.pop();
if (!tmp_q && !tmp_p) continue;
if ((tmp_q && !tmp_p) || (!tmp_q && tmp_p) || (tmp_q->val != tmp_p->val)) return false;
dq.push(tmp_p->right);
dq.push(tmp_q->right);
dq.push(tmp_p->left);
dq.push(tmp_q->left);
}
return true;

}


举报

相关推荐

0 条评论