题目:
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.
思路:
这道题是判断两个二叉树是否相等,各个节点和分支是否相等。依然使用递归遍历法,终结的条件是两个节点都为空,两个节点不一样,然后循环遍历左右节点,如果有一个节点不一样,那么返回的值始终为false。算法复杂度:O(N)
代码一:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q)
{
if( p == NULL && q == NULL )
{
return true;
}
else if( p == NULL && q != NULL )
{
return false;
}
else if( p != NULL && q == NULL )
{
return false;
}
bool bResult = true;
if( p->val == q->val )
{
bResult = true;
}
else
{
bResult = false;
}
bool bSameLeft = isSameTree(p->left, q->left);
bool bSameRight = isSameTree(p->right, q->right);
if( !bSameLeft )
{
bResult = false;
}
if( !bSameRight )
{
bResult = false;
}
return bResult;
}
};
代码二:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q)
{
if( (p == NULL && q != NULL) || (p != NULL && q == NULL ) )
{
return false;
}
if( p == NULL && q == NULL )
{
return true;
}
if( p->val != q->val )
{
return false;
}
return (isSameTree(p->left, q->left) && isSameTree(p->right, q->right));
}
};
总结:
1、二叉树的遍历:左节点递归遍历,右节点递归遍历。算法复杂度都是O(N)
2、两次提交成功,可以第一次是因为少了个";"号错误。
3、算法可以再优化,代码同样可以再优化。代码简洁、效率高、可读性强,这样才是一段好代码。代码二比一精简了一倍,但其可读性却更好了!
本文摘录于海阔天空的博客,作者: zjg555543,发布时间: 2015-07-27
网友评论