Skip to content

965. 单值二叉树

Posted on:2022年10月26日 at 14:18

965. 单值二叉树

leetcode 链接

解法一:深度优先遍历

/**
 * 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
 * @return {boolean}
 */
var isUnivalTree = function (root) {
  return dfs(root, root.val);
};

function dfs(root, val) {
  if (root) {
    return root.val === val && dfs(root.left, val) && dfs(root.right, val);
  }
  return true;
}

解法二:广度优先遍历(层序遍历)

/**
 * 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
 * @return {boolean}
 */
var isUnivalTree = function (root) {
  const val = root.val;
  const queue = [root];
  while (queue.length > 0) {
    const cur = queue.shift();
    if (cur.val !== val) {
      return false;
    }
    if (cur.left) {
      queue.push(cur.left);
    }
    if (cur.right) {
      queue.push(cur.right);
    }
  }
  return true;
};