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.

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

问题分析,简单的递归题,可以用先根遍历的递归算法,继续执行的判定标准是都空或都不空且值相同。

//code

class Solution {
public:
    bool isSameTree(TreeNode *p, TreeNode *q) {
        if(p && q && p->val == q->val)
        {
            bool b = isSameTree(p->left, q->left);
            if(b == false) return false;
            return isSameTree(p->right, q->right);
        }
        if(q == NULL && p == NULL)
        return true;
        else return false;
    }
};

说明:

            bool b = isSameTree(p->left, q->left);
            if(b == false) return false;
            return isSameTree(p->right, q->right);

这三条语句可以合并为一条语句,但是这里写的麻烦是为了让看官们更清楚的理解这个层次,我们看下一条语句的写法:

 return (isSameTree(p->left,q->left) && isSameTree(p->right, q->right));

其实是一样的,判断条件中的与操作是一种截断操作,即第一个条件为假,就不再判断以后的语句,直接返回判定结果。所以跟上面的本质是一致的,只不过要深入的挖掘下,这种层次感才能出来。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值