题目:
Same Tree
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.
来源:http://oj.leetcode.com/problems/same-tree/
思路:
判断树一个树节点是否相等三个条件: 是否有左节点, 是否有右节点, 值是否相等.
对两棵树同时进行深度遍历,每个结点都进行比较,当前两个结点值相同时,继续往下遍历,否则停止返回
C++ AC代码:
/**
* Definition for binary tree
* 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->val==q->val){
if(isSameTree(p->left,q->left) && isSameTree(p->right,q->right) )
return true;
else return false;
}
else return false;
}
};
运行时间:4ms