Leetcode PHP题解--D45 D45 872. Leaf-Similar Trees


D45 872. Leaf-Similar Trees

题目链接

872. Leaf-Similar Trees

题目分析

如果一个二叉树的左节点的后辈节点之和等于右节点的后辈节点,那么称该树为子节点相似树(直译的)。

思路

直接遍历左节点和右节点,遍历完判断左右节点之间是否相等即可。

最终代码

<?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 {
    function leafSimilar($root1, $root2) {
        $v1 = [];
        $this->sumVal($root1, $v1);
        $v2 = [];
        $this->sumVal($root2, $v2);
        return $v1 == $v2;
    }
    function sumVal($node, &$val){
        if($node->left){
            $this->sumVal($node->left,$val);
        }
        if($node->right){
            $this->sumVal($node->right, $val);
        }
        if(!$node->left && !$node->right){
            $val[]= $node->val;
        }
        return $val;
    }
}

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


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

<< 上一篇: Leetcode PHP题解--D45 872. Leaf-Similar Trees

>> 下一篇: Leetcode PHP题解--D46 893. Groups of Special-Equivalent Strings