leetcode 算法题:二叉树的堂兄弟节点

227 阅读1分钟

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

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

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

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

示例1:

image.png

示例2:

image.png

原题地址

判断是否是堂兄弟节点有两个关键点:深度相同一节父节点不同。因此可以在遍历整个二叉树时查找 x 和 y 并且记录对应的深度和父节点。

解法一:深度优先遍历

/**
 * 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) {
  var x_found = false, x_depth = 0, x_parent = null;
  var y_found = false, y_depth = 0, y_parent = null;
  var dfs = (node, parent, depth) => {
    if (!node) return
    if (node.val === x) {
      [x_found, x_depth, x_parent] = [true, depth, parent]
    }
    if (node.val === y) {
      [y_found, y_depth, y_parent] = [true, depth, parent]
    }

    if (x_found && y_found) return

    if (node.left) {
      dfs(node.left, node, depth + 1)
    }

    if (x_found && y_found) return

    if (node.right) {
      dfs(node.right, node, depth + 1)
    }
  }
  dfs(root, null, 0)
  if (x_found && y_found) {
    if (x_depth === y_depth && x_parent !== y_parent) {
      return true
    }
  }
  return false
};

解法二:广度优先遍历

/**
 * 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) {
  var x_found = false, x_depth = 0, x_parent = null;
  var y_found = false, y_depth = 0, y_parent = null;
  // 判断节点是否是 x 或 y
  var update = (node, parent, depth) => {
    if (node.val === x) {
      [x_found, x_depth, x_parent] = [true, depth, parent]
    }
    if (node.val === y) {
      [y_found, y_depth, y_parent] = [true, depth, parent]
    }
  }
  var dp = [[root, 0]]
  update(root, null, 0)
  while (dp.length) {
    var [node, depth] = dp.shift()
    if (node.left) {
      update(node.left, node, depth + 1)
      dp.push([node.left, depth + 1])
    }
    if (x_found && y_found) break
    if (node.right) {
      update(node.right, node, depth + 1)
      dp.push([node.right, depth + 1])
    }
    if (x_found && y_found) break
  }
  if (x_found && y_found) {
    if (x_depth === y_depth && x_parent !== y_parent) {
      return true
    }
  }
  return false
};