[leetcode] 100. Same Tree

来源:互联网 发布:免费聊天软件 编辑:程序博客网 时间:2024/06/05 08:47

Same Tree

描述

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)如果两棵树,一棵为空一棵不为空返回假;
(3)都不为空时,比较左右子树,左右子树都相同则返回真。

/** * 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;        }        else if (!p || !q)        {            return false;        }        if(p->val == q->val)        {            if(isSameTree(p->left, q->left)&&isSameTree(p->right, q->right))                return true;        }        return false;       }};
0 0
原创粉丝点击