Skip to content

Instantly share code, notes, and snippets.

@subramanian42
Created September 20, 2023 06:05
Show Gist options
  • Save subramanian42/c4093765573b91960cedb2374b2331a3 to your computer and use it in GitHub Desktop.
Save subramanian42/c4093765573b91960cedb2374b2331a3 to your computer and use it in GitHub Desktop.
binary-tree minimum value problem

binary-tree minimum value problem

Created with <3 with dartpad.dev.

import "dart:math";
import "dart:collection";
class Node
{
final int value;
Node? left;
Node? right;
static Node get empty => Node(0);
Node(this.value,{this.left,this.right});
}
class Stack<T extends Object >{
final _value = <T>[];
void push(T value) => _value.add(value);
T? pop() => (isEmpty) ? null : _value.removeLast();
T? get peek => (isEmpty) ? null : _value.last;
bool get isEmpty => _value.isEmpty;
bool get isNotEmpty => _value.isNotEmpty;
@override
String toString() => _value.toString();
}
class MinVal
{
static int calcMinDFS(Node root)
{ int minVal=double.maxFinite.toInt();
final stack =Stack<Node>();
stack.push(root);
while(stack.isNotEmpty){
final current = stack.pop();
if(current!=null) minVal = min(current.value,minVal);
if(current?.right!=null)stack.push(current!.right!);
if(current?.left!=null)stack.push(current!.left!);
}
return minVal;
}
static int calcMinBFS(Node root)
{ int minVal=double.maxFinite.toInt();
final queue = Queue<Node>();
queue.add(root);
while(queue.isNotEmpty){
final current = queue.removeFirst();
minVal = min(current.value,minVal);
if(current.left!=null)queue.add(current.left!);
if(current.right!=null)queue.add(current.right!);
}
return minVal;
}
}
void main() {
final a = Node(3);
final b = Node(11);
final c = Node(4);
final d = Node(2);
final e = Node(-1);
final f = Node(1);
a.left= b;
a.right = c;
b.left = d;
b.right = e;
c.right = f;
print("result is ${MinVal.calcMinDFS(a)}");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment