[路飞]_js算法:leetcode 993-二叉树的堂兄弟节点

43 阅读2分钟

leetcode 993. 二叉树的堂兄弟节点

问题描述: 在二叉树中,根节点位于深度 0 处,每个深度为 k 的节点的子节点位于深度 k+1 处。

如果二叉树的两个节点深度相同,但 父节点不同 ,则它们是一对堂兄弟节点

我们给出了具有唯一值的二叉树的根节点 root ,以及树中两个不同节点的值 x 和 y 。

只有与值 x 和 y 对应的节点是堂兄弟节点时,才返回 true 。否则,返回 false

示例 1:

输入: root = [1,2,3,4], x = 4, y = 3
输出: false

示例 2:

输入: root = [1,2,3,null,4,null,5], x = 5, y = 4
输出: true

示例 3:

输入: root = [1,2,3,null,4], x = 2, y = 3
输出: false

提示:

  • 二叉树的节点数介于 2 到 100 之间。
  • 每个节点的值都是唯一的、范围为 1 到 100 的整数。 思路: 深度优先遍历 !!!!!坑:js中函数不能直接修改实参(无论是字符串还是对象等数据类型)的值!!!!!!只能通过修改对象的具体属性,来修改实参!因为引用地址不变。

image.png

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} x
 * @param {number} y
 * @return {boolean}
 */
 var isCousins = function(root, x, y) {
   let d1=0,d2=0;
   var param={p1:null,p2:null};
  function getDeep(root,val,father){
  if(root==null)return -1;
  if(root.val==val)return 0;
  val==x?father.p1=root:father.p2=root;
  let l=0;
  l=getDeep(root.left,val,father)
  if(l!=-1)return l+1;
  val==x?father.p1=root:father.p2=root;//father在上面被改变了,因此要重新赋值
  l=getDeep(root.right,val,father)
  if(l!=-1)return l+1;
  return -1
}
   d1=getDeep(root,x,param)
   d2=getDeep(root,y,param)
   return d1==d2&&param.p1!=param.p2
};

思路2: 广搜 数据状态的定义比较重要

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
 function Data(node,deep,parent){
  this.node=node||null;
  this.deep=deep||0;
  this.parent=parent||null;
}
/**
 * @param {TreeNode} root
 * @param {number} x
 * @param {number} y
 * @return {boolean}
 */
var isCousins = function(root, x, y) {
let d1=d2=0;
   let p1=p2=null;
   let q=[];
   q.push(new Data(root,0))
   while(q.length){
     let cur=q[0];
     if(cur.node.val==x)d1=cur.deep,p1=cur.parent;
     if(cur.node.val==y)d2=cur.deep,p2=cur.parent;
     if(p1&&p2)break
     if(cur.node.left)q.push(new Data(cur.node.left,cur.deep+1,cur.node))
     if(cur.node.right) q.push(new Data(cur.node.right,cur.deep+1,cur.node))
     q.shift()
   }
return d1==d2&&p1!=p2
};