LeetCode(100) Same Tree

来源:互联网 发布:seo专业优化公司 编辑:程序博客网 时间:2024/05/21 03:28

题目

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);        }    }};
0 0
原创粉丝点击