Leetcode PHP题解--D45 872. Leaf-Similar Trees
D45 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; } }
若觉得本文章对你有用,欢迎用爱发电资助。
相关推荐
zyyjay 2020-11-09
xuebingnan 2020-11-05
samtrue 2020-11-22
stefan0 2020-11-22
yifangs 2020-10-13
songshijiazuaa 2020-09-24
hebiwtc 2020-09-18
天步 2020-09-17
83911535 2020-11-13
whatsyourname 2020-11-13
zhouyuqi 2020-11-10
Noneyes 2020-11-10
mathchao 2020-10-28
王志龙 2020-10-28
wwwsurfphpseocom 2020-10-28
diskingchuan 2020-10-23
savorTheFlavor 2020-10-23