检查两棵二叉树是否等价。等价的意思是说,首先两棵二叉树必须拥有相同的结构,而且每一个对应位置上的节点上的数都相等。ide
思路:
采用递归的思路:this
- 若是两棵树都是空,认为是等价的。
- 若是a.val == b.val,则只需考虑左右子树是否是等价二叉树。
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { public: /* * @param a: the root of binary tree a. * @param b: the root of binary tree b. * @return: true if they are identical, or false. */ bool isIdentical(TreeNode * a, TreeNode * b) { // write your code here if(a==NULL && b==NULL) return true; if(a==NULL || b==NULL) return false; if(a->val == b->val) { return isIdentical(a->left,b->left)&&isIdentical(a->right,b->right); } else return false; } };