LeetCode | 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.

思路:

树的问题大部分都是递归求解。

代码:

递归实现:

/**
 * Definition for binary tree
 * 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 == NULL && q == NULL){
            return true;
        }
        else if(p != NULL && q != NULL && p->val == q->val){
            return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
        }
        else{
            return false;
        }
    }
};

非递归实现:

/**
 * Definition for binary tree
 * 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) {
        queue<TreeNode*> node1;
        queue<TreeNode*> node2;
        
        if(p == NULL && q == NULL){
            return true;
        }
        else if(p != NULL && q != NULL && p->val == q->val){
            node1.push(p);
            node2.push(q);
            while(!node1.empty() && !node2.empty()){
                TreeNode* n1 = node1.front();
                node1.pop();
                TreeNode* n2 = node2.front();
                node2.pop();
                
                if(n1->left != NULL && n2->left != NULL && n1->left->val == n2->left->val){
                    node1.push(n1->left);
                    node2.push(n2->left);
                }
                else if(!(n1->left == NULL && n2->left == NULL))
                {
                    return false;
                }
                if(n1->right != NULL && n2->right != NULL && n1->right->val == n2->right->val){
                    node1.push(n1->right);
                    node2.push(n2->right);
                }
                else if(!(n1->right == NULL && n2->right == NULL))
                {
                    return false;
                }
            }
        }
        else{
            return false;
        }
        return true;
    }
};
    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/11785477
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞