zoukankan      html  css  js  c++  java
  • 【LeetCode】100. 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.

    提示:

    此题算是一种DFS的应用。

    代码:

    /**
     * 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) {
            // 如果p和q都是NULL,返回真
            if (!p && !q) return true;
            // 如果p和q一个是NULL,另一个不是,则返回假
            if (p && !q || !p && q) return false;
            // 剩下最后一种都不是NULL的情况,比较他们的数据
            if (p -> val != q->val) return false;
            // 对p和q的左右两个子节点进行递归
            return (isSameTree(p->left, q->left) && isSameTree(p->right, q->right));
        }
    };
  • 相关阅读:
    MongoDb
    js暴露内部方法属性等
    JS闭包
    k8s设计模式
    scrum
    死锁
    Linux下安装php 扩展fileinfo
    linux中whereis、which、find、location的区别和用法
    Linux 命令学习记录
    windows 下 redis 的安装及使用
  • 原文地址:https://www.cnblogs.com/jdneo/p/4738701.html
Copyright © 2011-2022 走看看