Last active
September 4, 2015 06:58
-
-
Save aalhour/58b3a206b123c916d3eb to your computer and use it in GitHub Desktop.
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
public class TreeNode<T> where T : IComparable<T> | |
{ | |
public T Value { get; set; } | |
public TreeNode<T> Left { get; set; } | |
public TreeNode<T> Right { get; set; } | |
public TreeNode<T> Parent { get; set; } | |
} | |
public static class TreeTraversalIterative | |
{ | |
public static void PreOrderTraversal<T>(TreeNode<T> root, Action<T> action) where T : IComparable<T> | |
{ | |
if(root == null) | |
return; | |
var stack = new System.Collections.Generic.Stack<TreeNode<T>>(); | |
var curr = root; | |
while(true) { | |
if(curr != null) { | |
action(curr.Value); | |
stack.Push(curr.Right); | |
curr = curr.Left; | |
} else { | |
if(stack.Count == 0) { | |
break; | |
} else { | |
curr = stack.Pop(); | |
} | |
}//end-if-else | |
}//end-while | |
} | |
public static void InOrderTraversal<T>(TreeNode<T> root, Action<T> action) where T : IComparable<T> | |
{ | |
if(root == null) | |
return; | |
var stack = new System.Collections.Generic.Stack<TreeNode<T>>(); | |
var curr = root; | |
while(true) { | |
if(curr != null) { | |
stack.Push(curr); | |
curr = curr.Left; | |
} else { | |
if(stack.Count == 0) { | |
break; | |
} else { | |
curr = stack.Pop(); | |
action(curr.Value); | |
curr = curr.Right; | |
} | |
}//end-if-else | |
}//end-while | |
} | |
public static void PostOrderTraversal<T>(TreeNode<T> root, Action<T> action) where T : IComparable<T> | |
{ | |
if(root == null) | |
return; | |
TreeNode<T> prev = null; | |
var stack = new System.Collections.Generic.Stack<TreeNode<T>>(); | |
stack.Push(root); | |
while(stack.Count > 0) { | |
var curr = stack.Peek(); | |
if(prev == null || prev.Left == curr || prev.Right == curr) { | |
if(curr.Left != null) { | |
stack.Push(curr.Left); | |
} else if(curr.Right != null) { | |
stack.Push(curr.Right); | |
} | |
} else if (prev == curr.Left) { | |
if(curr.Right != null) | |
stack.Push(curr.Right); | |
} else { | |
action(curr.Value); | |
stack.Pop(); | |
} | |
prev = curr; | |
}//end-while | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment