Tuesday, July 22, 2014

In-Order Flatten A Binary Tree to Linked List

In-order flatten binary tree, the idea here is similar to in-order traverse of the tree, keep a pointer to previous node visited, then link current node with previous.



public static void FlattenABinaryTreetoLinkedListInOrder(Node root){
Stack<Node> s = new Stack<Node>();
Node c = root;
Node pre = null;
while(!s.isEmpty()||c!=null){
if(c!=null){
s.push(c);
c = c.left;
}
else{
Node n = s.pop();
if(pre!=null){
pre.right = n;
pre.left = null;
}
pre = n;
n = n.right;
}
}
}

No comments:

Post a Comment