内容简介:在二叉树中,若两个叶子节点的层数相同,但具有不同的父节点,那么这两个节点互为cousin节点。给定一个二叉树及x、y两个节点,返回x、y两个节点在二叉树中,是否互为cousin节点。
D76 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》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Learning Processing
Daniel Shiffman / Morgan Kaufmann / 2008-08-15 / USD 49.95
Book Description Teaches graphic artists the fundamentals of computer programming within a visual playground! Product Description This book introduces programming concepts in the context of c......一起来看看 《Learning Processing》 这本书的介绍吧!