code.ashish.me

Atom feed

Recently added: 128 Longest Consecutive Sequence, 347 Top K Frequent Elements, 045 Jump Game 2, 228 Summary Ranges, 219 Contains Duplicate 2

965 Univalued Binary Tree

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

function TreeNode(val) {
  this.val = val
  this.left = this.right = null
}

const univaluedBinaryTree = root => {
  let flag = true
  const traverse = (root, value) => {
    if (root == null) {
      return
    }
    if (value !== root.val) {
      flag = false
      return
    }
    root.left && traverse(root.left, value)
    root.right && traverse(root.right, value)
  }
  traverse(root, root.val)
  return flag
}

test('univaluedBinaryTree', () => {
  const t1 = new TreeNode(1)
  t1.right = new TreeNode(1)
  t1.left = new TreeNode(1)
  t1.left.left = new TreeNode(5)
  t1.left.right = new TreeNode(1)
  // t1.right.right = new TreeNode(1)
  expect(univaluedBinaryTree(t1)).toEqual(false)
})

Created 2020-12-06T17:28:03+05:30 · Edit