Leetcode PHP题解--D101 100. Same Tree


D101 100. Same Tree

题目链接

100. Same Tree

题目分析

判断给定的两颗树是否相等。即对应位置的对应值是否都相等。

思路

同时逐个遍历,一遇到不相等的就直接返回false。

二叉树的遍历就不细说了。

最终代码

<?php
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     public $val = null;
 *     public $left = null;
 *     public $right = null;
 *     function __construct($value) { $this->val = $value; }
 * }
 */
class Solution {

    /**
     * @param TreeNode $p
     * @param TreeNode $q
     * @return Boolean
     */
    function isSameTree($p, $q) {
        if(is_null($p) && is_null($q)){
            return true;
        }
        if((is_null($p) && !is_null($q)) || (!is_null($p)&&is_null($q))){
            return false;
        }
        if($p->val !== $q->val){
            return false;
        }
        $l = $this->isSameTree($p->left, $q->left);
        if($l === false){
            return false;
        }
        $r = $this->isSameTree($p->right, $q->right);
        if($r === false){
            return false;
        }
        return true;
    }
}

若觉得本文章对你有用,欢迎用爱发电资助。


点赞 取消点赞 收藏 取消收藏

<< 上一篇: Leetcode PHP题解--D100 387. First Unique Character in a String

>> 下一篇: Leetcode PHP题解--D102 383. Ransom Note