package Sort.TreeSort;

import java.util.ArrayDeque;
import java.util.Deque;

public class TreeNode {
	TreeNode left;
	TreeNode right;
	int value;
	/**
	 * @param value
	 */
	public TreeNode(int value) {
		this.value = value;
		left=null;
		right=null;
	}
	
	private void insert(TreeNode node) {
		if (node.value < this.value) {
			if (left==null) left=node;
			else left.insert(node);
		} else {
			if (right==null) right=node;
			else right.insert(node);
		}
	}
	
	public void insert(int newVal) {
		this.insert(new TreeNode(newVal));
	}
	
	public void getVals(int[] arr) {
		fillResult(0,arr);
	}
	
	public void getVals2(int[] arr) {
		Deque<TreeNode> stack = new ArrayDeque<TreeNode>();
		TreeNode n = this;
		int pos=0;
		while(n != null) {
			stack.push(n);
			n=n.left;
		}
		while(stack.size()>0) {
			n=stack.pop();
			arr[pos]=n.value;
			pos++;
			if (n.right!=null) {
				n=n.right;
				while(n != null) {
					stack.push(n);
					n=n.left;
				}
			}
		}
	}
	
	private int fillResult(int pos,int[] arr) {
		if (this.left!=null) pos=this.left.fillResult(pos,arr);
		arr[pos]=value;
		pos++;
		if (this.right!=null) pos=this.right.fillResult(pos, arr);
		return pos;
	}
	
	public void print() {
		print("","","");
	}
	
	private void print(String tpref,String mpref,String bpref) {
		if (left!=null) left.print(tpref+"   ",tpref+"  +",tpref+"  |");
		System.out.println(mpref +"--" + value);
		if (right!=null) right.print(bpref+"  |",bpref+"  +",bpref+"   ");
	}

}
