Leetcode PHP题解--D76 993. Cousins in Binary Tree

栏目: PHP · 发布时间: 6年前

内容简介:在二叉树中,若两个叶子节点的层数相同,但具有不同的父节点,那么这两个节点互为cousin节点。给定一个二叉树及x、y两个节点,返回x、y两个节点在二叉树中,是否互为cousin节点。

D76 993. Cousins in Binary Tree

题目链接

993. Cousins in Binary Tree

题目分析

在二叉树中,若两个叶子节点的层数相同,但具有不同的父节点,那么这两个节点互为cousin节点。

给定一个二叉树及x、y两个节点,返回x、y两个节点在二叉树中,是否互为cousin节点。

思路

因为x和y在二叉树中唯一,故我们可已先遍历整个二叉树,把当前节点的值作为数组的键,把当前的层数作为值,存进一个数组中。

遍历完成后,直接判断数组中对应的值是否相同即可。

最终代码

<?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 $root
     * @param Integer $x
     * @param Integer $y
     * @return Boolean
     */
    public $data = [];
    public $level = [];
    function isCousins($root, $x, $y) {
        $this->inOrder($root, 0, 0);
        return ($this->prnt[$x] != $this->prnt[$y]) && ($this->level[$x] == $this->level[$y]);
    }
    function inOrder($root, $crnt, $level){
        if(is_null($root)){
            return;
        }
        $this->prnt[$root->val] = $crnt;
        $this->level[$root->val] = $level;
        $level++;
        $this->inOrder($root->left, $root->val, $level);
        $this->inOrder($root->right, $root->val, $level);
    }
}

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


以上所述就是小编给大家介绍的《Leetcode PHP题解--D76 993. Cousins in Binary Tree》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Web Data Mining

Web Data Mining

Bing Liu / Springer / 2006-12-28 / USD 59.95

Web mining aims to discover useful information and knowledge from the Web hyperlink structure, page contents, and usage data. Although Web mining uses many conventional data mining techniques, it is n......一起来看看 《Web Data Mining》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

在线进制转换器
在线进制转换器

各进制数互转换器

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码