- 先序遍历
- 遍历的本级函数:比较两个二叉树当前节点值是否相等
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
#include <fstream>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root1 TreeNode类
* @param root2 TreeNode类
* @return bool布尔型
*/
bool isSameTree(TreeNode* root1, TreeNode* root2) {
// write code here
if (root1 == nullptr && root2 == nullptr) {
return true;
}
if (root1 == nullptr && root2 != nullptr) return false;
if (root1 != nullptr && root2 == nullptr) return false;
if(root1->val != root2->val) return false;
bool left = isSameTree(root1->left, root2->left);
bool right = isSameTree(root1->right, root2->right);
return left && right;
}
};