LeetCode 100. Same Tree

来源:互联网 发布:威少最新体测数据 编辑:程序博客网 时间:2024/06/16 11:06

100. Same Tree

Descripiton

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.

Solution

  • 题意即判断两个二叉树是否相同,要求结构相同并且对应位置的节点值也相等。
  • 用递归很容易实现,对空节点的几种情况特判之后,判断当前节点值是否相同、左子树和右子树是否相同。代码如下。
class Solution {public:    bool isSameTree(TreeNode* p, TreeNode* q) {        if (p == NULL && q == NULL) return true;        if ((p == NULL && q != NULL) || (p != NULL && q == NULL)) return false;        if (p->val == q->val && isSameTree(p->left,q->left) && isSameTree(p->right,q->right))             return true;        else             return false;    }};
原创粉丝点击