Skip to content

Instantly share code, notes, and snippets.

@tonyxu-io
Last active June 25, 2018 03:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonyxu-io/7e8383cb8bd0c3424d040f5d3e952b6a to your computer and use it in GitHub Desktop.
Save tonyxu-io/7e8383cb8bd0c3424d040f5d3e952b6a to your computer and use it in GitHub Desktop.
Tree #DataStructureAlgorithms
// Tree Node Definition
function TreeNode(val) {
this.val = val;
this.left = this.right = null;
}
// Tree Creation
var t = new TreeNode(10)
t.left = new TreeNode(-2)
t.right = new TreeNode(6)
t.left.left = new TreeNode(8)
t.left.right = new TreeNode(-4)
t.right.left = new TreeNode(7)
t.right.right = new TreeNode(5)
// Check if a given binary tree is a sum tree
var sumTree = function(root) {
if (root === null) {
return true
}
if (root.left === null && root.right === null) {
return true
}
return root.val === addNodes(root.left) + addNodes(root.right)
}
var addNodes = function(root) {
if (root === null) {
return 0
}
return root.val + addNodes(root.left) + addNodes(root.right)
}
// Check if a binary tree is a binary search tree (BST)
function checkIfBinaryTreeIsBST (root, min = Number.MIN_VALUE, max = Number.MAX_VALUE) {
if (root === null) {
return true
}
if (root.val < min || root.val > max) {
return false
}
return checkIfBinaryTreeIsBST(root.left, min, root.val - 1) && checkIfBinaryTreeIsBST(root.right, root.val + 1, max)
}
// Convert binary tree to a sum tree
var convertToSumTree = function(root) {
if (root === null) {
return 0
}
var temp = root.val
root.val = convertToSumTree(root.left) + convertToSumTree(root.right)
return root.val + temp
}
// Get size of a tree
function size(root) {
if (root === null) {
return 0
} else {
return size(root.left) + size(root.right) + 1
}
}
// Print Tree
function printTree(root) {
if (root === null) {
return
}
printTree(root.left)
process.stdout.write(`${root.val.toString()} `);
printTree(root.right)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment