Skip to content

Instantly share code, notes, and snippets.

@subramanian42
Created September 9, 2023 15:30
Show Gist options
  • Save subramanian42/7fd220aa7a50030b772e40bc4d635ee2 to your computer and use it in GitHub Desktop.
Save subramanian42/7fd220aa7a50030b772e40bc4d635ee2 to your computer and use it in GitHub Desktop.
binary tree DFS
class Node
{
final String value;
Node? left;
Node? right;
static Node get empty => Node("");
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 DFS{
static void depthFirstValues(Node root)
{
final stack = Stack<Node>();
stack.push(root);
while(stack.isNotEmpty){
final current = stack.pop();
if(current!=null)
{print(current.value);}
if(current?.right!=null)
{
stack.push(current!.right!);
}
if(current?.left!=null)
{
stack.push(current!.left!);
}
}
}
}
void main() {
final a = Node('a');
final b= Node('b');
final c= Node('c');
final d =Node('d');
final e = Node('e');
final f = Node('f');
a.left=b;
a.right=c;
b.left=d;
b.right=e;
c.left=f;
DFS.depthFirstValues(a);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment