Created with <3 with dartpad.dev.
Created
September 9, 2023 15:30
-
-
Save subramanian42/7fd220aa7a50030b772e40bc4d635ee2 to your computer and use it in GitHub Desktop.
binary tree DFS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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