题目:
提供两棵树的根节点,让你判断这两棵树是否相似;限定用递归写法
树相似的定义:形状相同即相似,如果两树是空树,也相似
核心代码:
bool isSimilar(TreeNode* root1 ,TreeNode* root2){
if(!root1 && !root2) return true;
if((!root1&&root2) || (root1&&!root2)) return false;
//能走到这就证明肯定为非空,因此不用再特别判断;
return (isSimilar(root1->left,root2->left) && isSimilar(root1->right ,root2->right));
}
完整代码:
#include <bits/stdc++.h>
using namespace std;
//定义树节点结构体
struct TreeNode{
char val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(char x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(char x, TreeNode *left, TreeNode *right) : val(x),left(left), right(right) {}
};
bool isSimilar(TreeNode* root1 ,TreeNode* root2){
if(!root1 && !root2) return true;
if((!root1&&root2) || (root1&&!root2)) return false;
//能走到这就证明肯定为非空,因此不用再特别判断;
return (isSimilar(root1->left,root2->left) && isSimilar(root1->right ,root2->right));
}
int main()
{
//建树
TreeNode *root1 = new TreeNode('A',
new TreeNode('B',
new TreeNode('D'),
new TreeNode('E')),
new TreeNode('C',
new TreeNode('F'),
new TreeNode('G')));
//建树
TreeNode *root2 = new TreeNode('A',
new TreeNode('B',
new TreeNode('D'),
new TreeNode('E')),
new TreeNode('C',
new TreeNode('F'),
new TreeNode('G')));
return 0;
}