本文主要是介绍leetcode 刷题之路 10 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.
判断两个树是否相同,相同的标准可以递归描述为根节点值相同,并且左右子树相同,根据这个定义可以写出以下程序:
my accepted answer:
/*** 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;if ((p == NULL&&q != NULL) || (p != NULL&&q == NULL)) return false;return p->val == q->val&&isSameTree(p->left, q->left) && isSameTree(p->right,q->right);return isSameTree(p, q);}
};
这篇关于leetcode 刷题之路 10 Same Tree的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!