dainiwan的专栏

题目: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) {} * }; */class Solution {public:bool isSameTree(TreeNode *p, TreeNode *q) {if(p==nullptr && q== nullptr)return true;if(p==nullptr && q!=nullptr)return false;if(p!=nullptr && q==nullptr)return false;if(p->val != q->val)return false;elsereturn isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);}};

人生最好的旅行,就是你在一个陌生的地方,

dainiwan的专栏

相关文章:

你感兴趣的文章:

标签云: