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.
基本思路:
进行递归操作,判断两个树是否相等。
1. 两树若都为空树,则相等。
2. 两树都不空;根结点的值相等;左子树相等;右子树相等。则该树相等。
在leetcode上实际执行时间为2ms。
/** * Definition for a binary tree node. * 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 && !q) return true; return p && q && p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right); } };
时间: 2024-09-27 01:41:18