Skip to content

Latest commit

 

History

History
56 lines (46 loc) · 1.19 KB

965.单值二叉树.md

File metadata and controls

56 lines (46 loc) · 1.19 KB

965.单值二叉树

/*
 * @lc app=leetcode.cn id=965 lang=typescript
 *
 * [965] 单值二叉树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function isUnivalTree(root: TreeNode | null): boolean {

// @lc code=end

解法 1: BFS

function isUnivalTree(root: TreeNode | null): boolean {
  if (!root) return true
  const queue = [root],
    target = root.val
  for (let node of queue) {
    if (node.val !== target) return false
    for (let next of [node.left, node.right]) if (next) queue.push(next)
  }
  return true
}

Case

test.each([
  { input: { root: [1, 1, 1, 1, 1, null, 1] }, output: true },
  { input: { root: [2, 2, 2, 5, 2] }, output: false },
])('input: root = $input.root', ({ input: { root }, output }) => {
  expect(isUnivalTree(BinaryTree.deserialize(root))).toBe(output)
})