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.
判断两个给定的树是否相同,不追求效率,简单编码可以使用深度优先,递归的方式
先判断两个树p和q是否为空,为空返回true,在不为空时,若p和q的左子树有一个为空或是右子树有一个为空,则一定返回false
然后,继续递归,对p和q的左子树和右子树分别进行isSame(p, q)运算
C语言代码:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ bool isSameTree(struct TreeNode* p, struct TreeNode* q) { if(p == NULL && q == NULL) { return 1; } else if(p == NULL || q == NULL) { return 0; } if(p->val != q->val) { return 0; } return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); }
时间: 2024-10-16 15:40:38