LeetCode 100 Same Tree

来源:互联网 发布:c语言之父的一段代码 编辑:程序博客网 时间:2024/06/03 17:11

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.


/** * 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;        if(!p || !q)            return false;        bool flag = isSameTree(p?p->left:nullptr,q?q->left:nullptr);            if(!flag)                return false;        flag = isSameTree(p?p->right:nullptr,q?q->right:nullptr);            if(!flag)                return false;        if(p->val == q->val)            return true;        return false;    }};


对树进行操作,用的基本都是递归。

对于我上面的代码更加简洁的代码:

bool isSameTree(TreeNode *p, TreeNode *q) {    if (p == NULL || q == NULL) return (p == q);    return (p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right));}



原创粉丝点击