Same Tree

来源:互联网 发布:如何复制筛选后的数据 编辑:程序博客网 时间:2024/06/06 12:45
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.

思路:给定两个二叉树,判断两棵树的是否是相同的。相同的定义是两棵树的结构相同且在相同位置上的节点val值也相等。

递归的考虑这个问题:

(1)当两棵树的根节点p和q都为NULL的时候,两者结构相同且val相等。

(2)当其中一个为NULL一个不为NULL的时候,两者结构不同,返回false。

(3)当两者都不为NULL的时候,在两者根节点值相等且左右两个子树都是相同的时候,整个原来的两个树是相同的。

对于左右子树的处理也是类似的,因此可以使用递归的方式解决,代码如下所示。

/** * 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;        if((p&&!q)||(!p&&q))            return false;        return p->val==q->val&&isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);    }};


0 0
原创粉丝点击