993. Cousins in Binary Treephp
在二叉樹中,若兩個葉子節點的層數相同,但具備不一樣的父節點,那麼這兩個節點互爲cousin節點。node
給定一個二叉樹及x、y兩個節點,返回x、y兩個節點在二叉樹中,是否互爲cousin節點。數組
由於x和y在二叉樹中惟一,故咱們可已先遍歷整個二叉樹,把當前節點的值做爲數組的鍵,把當前的層數做爲值,存進一個數組中。this
遍歷完成後,直接判斷數組中對應的值是否相同便可。.net
<?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); } }
若以爲本文章對你有用,歡迎用愛發電資助。code