You are viewing a single comment's thread. Return to all comments →
Had to build classes from scratch for R
library(magrittr) Node <- setRefClass( "Node", fields = list( info = "numeric", left = "ANY", right = "ANY" ), methods = list( initialize = function(info) { .self$info <- info .self$left <- NULL .self$right <- NULL }, toString = function() { as.character(.self$info) } ) ) BinarySearchTree <- setRefClass( "BinarySearchTree", fields = list( root = "ANY" ), methods = list( initialize = function() { .self$root <- NULL }, create = function(val) { newNode <- Node$new(info = val) if (is.null(.self$root)) { .self$root <- newNode } else { current <- .self$root repeat { if (val < current$info) { if (!is.null(current$left)) { current <- current$left } else { current$left <- newNode break } } else if (val > current$info) { if (!is.null(current$right)) { current <- current$right } else { current$right <- newNode break } } else { break } } } } ) ) height <- function(root) { if (is.null(root)) { return(-1) } left_height <- height(root$left) right_height <- height(root$right) max(left_height, right_height) + 1 } stdin <- file('stdin', 'r') inp <- readLines(stdin, n = 2, warn = FALSE) close(stdin) rootInput <- as.integer(inp[1]) treeInput <- strsplit(inp[2], " ") %>% unlist %>% as.integer bst <- BinarySearchTree$new() for (n in treeInput) { bst$create(n) } cat(height(bst$root), "\n")
Seems like cookies are disabled on this browser, please enable them to open this website
Tree: Height of a Binary Tree
You are viewing a single comment's thread. Return to all comments →
Had to build classes from scratch for R