Definition for a binary tree node. public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } }
| 8 | * } |
| 9 | */ |
| 10 | class CBTInserter { |
| 11 | TreeNode root; |
| 12 | Queue<TreeNode> q = new LinkedList<TreeNode>(); |
| 13 | // This queue is a helper to reduce load on insert function.. |
| 14 | public CBTInserter(TreeNode root) { |
| 15 | this.root = root; |
| 16 | Queue<TreeNode> temp = new LinkedList(q); |
| 17 | temp.add(root); |
| 18 | q.add(root); |
| 19 | // Prepare a queue for the for our insert function... |
| 20 | while(!temp.isEmpty()){ |
| 21 | TreeNode t = temp.poll(); |
| 22 | if(t.left!=null){ |
| 23 | temp.add(t.left); |
| 24 | q.add(t.left); |
| 25 | } |
| 26 | if(t.right!=null){ |
| 27 | temp.add(t.right); |
| 28 | q.add(t.right); |
| 29 | } |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | |
| 34 | public int insert(int v) { |
| 35 | TreeNode n = new TreeNode(v); |
| 36 | n.left = n.right = null; |
| 37 | TreeNode parent = null; |
| 38 | // Add new node to the queue... |
| 39 | q.add(n); |
| 40 | while(true){ |
| 41 | parent = q.peek(); |
| 42 | // If the node's left is null then, insert there. |
| 43 | if(parent.left==null){ |
| 44 | parent.left = n; |
| 45 | break; |
| 46 | } |
| 47 | // If the node's right is null then, insert there.... |
| 48 | // Now this node can never become parent of new node, so remove it from the queue |
| 49 | if(parent.right==null){ |
| 50 | parent.right = n; |
| 51 | q.poll(); |
| 52 | break; |
| 53 | } |
| 54 | // else it means the node has left and right children which are not null... so remove it from queue. |
| 55 | q.poll(); |
| 56 | } |
| 57 | // Return the parent's value to the caller function... |
| 58 | return parent.val; |
| 59 | } |
| 60 | |
| 61 | public TreeNode get_root() { |
| 62 | return root; |
| 63 | } |
| 64 | } |
nothing calls this directly
no outgoing calls
no test coverage detected