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.

分析

判断两个二叉树是否相同。

采用递归的思想,当节点关键字以及左右子树均相同时,此两颗二叉树才相同;

AC代码

/**
 * 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) {
        //如果两个二叉树均为空,则返回true
        if (!p && !q)
        {
            return true;
        }
        //如果两者其一为空树,则返回false
        else if (!p || !q)
        {
            return false;
        }
        else{
            if (p->val != q->val)
                return false;
            else
                return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
        }
    }
};

相关文章:

  • 2021-05-20
  • 2021-07-30
  • 2022-12-23
  • 2022-12-23
  • 2021-08-02
  • 2021-12-26
  • 2021-10-06
猜你喜欢
  • 2021-09-13
  • 2022-01-05
  • 2021-09-10
  • 2022-03-09
  • 2021-09-04
  • 2021-09-02
相关资源
相似解决方案