您的位置:首页 > 职场人生

[面试算法题]比较二叉树异同-leetcode学习之旅(5)

2015-11-18 22:37 288 查看

问题描述

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.


和Balanced Binary Tree那题很像。定义T(p)为以p为根的树,T(p) = T(q)需要符合两个条件:

(1) p和q等价,这里的等价有两种情况:p = q = NULL,或p、q都不为NULL且p->val = q->val。反过来说当p和q中只有一个为NULL,或者p->val != q->val时p和q不等价。

(2) 如果p和q都不为NULL,则要求T(p->left) = T(q->left)且T(p->right) = T(q->right)。

想清楚以上两点,基本上就秒杀了。


c++实现

/**
* 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 && !q) return true;
if((!p && q) || (p && !q)) return false;
if(p->val != q->val) return false;
return isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: