public Boolean IsBinarySearchTree(Bnode <int> root) { if (root == null) { return(false); } if (!IsBinarySearchTree(root.left)) { return(false); } if (prev != null && prev.data > root.data) { return(false); } //save the previous node to comare with current prev = root; if (!IsBinarySearchTree(root.right)) { return(false); } return(true); }
public void insert(Bnode <int> node) { if (root == null) { root = node; return; } var cur = root; while (cur != null) { if (node.data < cur.data) { if (cur.left == null) { cur.left = node; return; } cur = cur.left; } else { if (cur.right == null) { cur.right = node; return; } cur = cur.right; } } }
public int MinDepthBinaryTree(Bnode <int> root) { //base if (root == null) { return(depth); } if (root.left == null || root.right == null) { return(depth); } depth++; int lefth = MinDepthBinaryTree(root.left); int righth = MinDepthBinaryTree(root.right); if (lefth > righth) { return(righth); } else { return(lefth); } }
public Boolean IsIdentical(Bnode <int> Tree1, Bnode <int> Tree2) { //base case both null or terminate condition if (Tree1 == null && Tree2 == null) { return(true); } //Either of Two Tree reached null that means root2 is not sub tree // becuase both should end with null togather, otherwise return false if (Tree1 == null || Tree2 == null) { return(false); } //In Traverse, you find that if data doesn't match, then //Simply return false, because every node of Tree1 must match with every node of Tree2 if (Tree1.data != Tree2.data) { return(false); } // Traverse In-order return(IsIdentical(Tree1.left, Tree2.left) && IsIdentical(Tree1.right, Tree2.right)); }
// Definition : height difference between left subtree and right subtree no more than 1 // is balanced or not checked by checking height of the right and left sub trees // Steps // if tree empty then tree is balanced // else // leftheight = get the height of the left subtree // rightheight = get the height of the right subtree // if leftheight - rightheigh <=1 ( not more than 1) declare balanced public Boolean Isbalanced(Bnode <int> root) { //base case if (root == null) { return(true); } int leftSubTreeHeight = Height(root.left); int rightSubTreeHeight = Height(root.right); if (!(Math.Abs(leftSubTreeHeight - rightSubTreeHeight) <= 1)) { return(false); } if (!Isbalanced(root.left)) { return(false); } if (!Isbalanced(root.right)) { return(false); } return(true); }
/// <summary> /// opposite of successor /// find node with maximum value in a left sub tree from x /// if left sub tree doens't exist then do the opposite thing but /// same way that i did for successor /// \ <---Predecessor /// \ /// \ /// \ /// X //no left tree / /// </summary> /// <param name="root"></param> /// <param name="x">X node for which we find Predecessor</param> /// <returns></returns> public Bnode <int> InOrderPredecessor(Bnode <int> root, Bnode <int> x) { if (x.left != null) { return(Max(x.left)); } Bnode <int> pred = null; while (root != null) { if (x.data < root.data) { root = root.left; } else if (x.data > root.data) { pred = root; root = root.right; } else { break; } } return(pred); }
/// <summary> /// successor : Minimum value in a right sub tree from a given node x e.g X here ///if right tree is not there then, /// successor is furtherst parent of x that you get following right branches /// / <------Successor /// / /// / /// / /// X /// \ No right Sub Tree /// </summary> /// <param name="root">Tree</param> /// <param name="x">X node for which we find Successor</param> /// <returns></returns> public Bnode <int> InOrderSuccesor(Bnode <int> root, Bnode <int> x) { //If right sub tree exist from node x node, //then find minimum value in right sub tree which is succ if (x.right != null) { return(Min(x.right)); } Bnode <int> suc = null; //If right tree doens't exist, do the following while (root != null) { if (x.data < root.data) { suc = root; root = root.left; } else if (x.data > root.data) { root = root.right; } else { break; } } return(suc); }
//Breadth First search is a level-order binary tree traversal //(linked list n- connection problem solution) // And remeber that BFS use Queue data structure public void printOrderLevelBtree(Bnode <int> root) { Queue <Bnode <int> > q = new Queue <Bnode <int> >(); if (root == null) { return; } else { q.enqueue(root); } while (true) // there should be a terminate condition like queue should be empty but //I terminated when dequeue operation is null no { // no node need have adjanct right and left vertex to visit now. Bnode <int> node = q.dequeue(); if (node != null) { Console.WriteLine(node.data); } else { return; } if (node.right != null) { q.enqueue(node.right); } if (node.left != null) { q.enqueue(node.left); } } }
/// <summary> /// Looks like you need to traverse every node ( in order traversal) /// but in order traversal return back when you find null /// here you find a node1/node2 then you return /// In return from left you also check right side for another node2 /// if you find right side also then found node in opposite side. and return root /// otherwise return right or left ( from where you returned) /// </summary> /// <param name="root"></param> /// <param name="node1"></param> /// <param name="node2"></param> /// <returns></returns> public Bnode <int> FindLCA(Bnode <int> root, Bnode <int> node1, Bnode <int> node2) { if (root == null) { return(null); } if (root.data == node1.data || root.data == node2.data) { return(root); // } //in-order traversal returns when null or found a either node1 or node2 Bnode <int> left = FindLCA(root.left, node1, node2); Bnode <int> right = FindLCA(root.right, node1, node2); //if you found node1 and node 2 opposite side (left and right return root) if (left != null && right != null) { return(root); } // don't find right becasue it was below in left subtree (DFS) // but you return because you find node1/node2 in left and didn't do DFS and back if (left != null) { return(left); } // don't find left becasue it was below there in a right subtree (DFS) // but you returned because you find node1/node2 in right and didn't do DFS and back else { return(right); // don't find left because you } }
//Minimum value always deep left side of the tree // you can do this prog using while loop public Bnode <int> Min(Bnode <int> root) { if (root.left != null) { Min(root.left); } return(root); }
//Minimum value always deep right side of the tree // you can do this prog using while loop public Bnode <int> Max(Bnode <int> root) { if (root.right != null) { Max(root.right); } return(root); }
public void Serialize(Bnode <int> root) { if (root == null) { Console.WriteLine("#"); return; } Console.WriteLine("{0} ", root.data); Serialize(root.left); Serialize(root.right); }
// print height of the tree public int findHeight(Bnode <int> root) { if (root == null) { return(0); } int heighleft = findHeight(root.left); int heightright = findHeight(root.right); return(Math.Max(heighleft, heightright) + 1); }
//To print leaf node is simply a in-order traversal //but print the visit node which has left and right node=null public void printleafnodes(Bnode <int> root) { if (root == null) { return; } printleafnodes(root.left); if (root.right == null && root.left == null) { Console.WriteLine(root.data); } printleafnodes(root.right); }
public void fixprevPointer(Bnode <int> root) { //Fix the left pointer first //root is current node if (root == null) { return; } fixprevPointer(root.left); root.left = prev; prev = root; fixprevPointer(root.right); }
//Depth First Search (goes deeper and deeper till encounter null) public void inorderTraverse(Bnode <int> anode) { Bnode <int> cur = anode; if (cur.left != null) { inorderTraverse(cur.left); } Console.WriteLine(cur.data); if (cur.right != null) { inorderTraverse(cur.right); } }
// public void fixNextPointer(Bnode <int> root) { //reach the right most node, which is last node in ddl while (root != null && root.right != null) { root = root.right; } //iterate through left pointer that we set previosly //in that aslo while (root != null && root.left != null) { prev = root; root = root.left; //next root.right = prev; //next points to prev } }
public void PathRootToleafRec(Bnode <int> node, int length) { if (node == null) { return; } Path[length] = node; length++; if (node.left == null && node.right == null) { print(length); } PathRootToleafRec(node.left, length); PathRootToleafRec(node.right, length); }
//traverse left only public void printleftEdge(Bnode <int> root) { if (root == null) { return; } //this codition doesn't print the leaf node if (root.left != null) { Console.WriteLine(root.data); printleftEdge(root.left); } else if (root.right != null) { Console.WriteLine(root.data); printleftEdge(root.right); } }
//Do in order traversal and print kth element by checking condition public void inorder(Bnode <int> root) { Bnode <int> cur = root; if (cur == null) { return; } inorder(cur.left); i++; if (i == k) { Console.WriteLine(cur.data); } inorder(cur.right); }
//traverse right only public void printrightEdge(Bnode <int> root) { if (root == null) { return; } if (root.right != null) { printrightEdge(root.right); Console.WriteLine(root.data); //print on backtrack } else if (root.left != null) { printrightEdge(root.left); Console.WriteLine(root.data); // print on backtrack } }
public int Height(Bnode <int> root) { if (root == null) { return(0); } int left = Height(root.left); int right = Height(root.right); if (left > right) { return(left + 1); } else { return(right + 1); } }
public Bnode <int> SortedArrayToBST(int[] array, int start, int end) { //base case if (start > end) { return(null); } int mid = (start + end) / 2; Bnode <int> node = new Bnode <int>(array[mid]); //recursivly construct left subtree node.left = SortedArrayToBST(array, start, mid - 1); //recursivly construct right subtree node.right = SortedArrayToBST(array, mid + 1, end); return(node); }
public Bnode <int> findCommonAncestor(Bnode <int> root, Bnode <int> p, Bnode <int> q) { if (root == null) { return(null); } // p and q is left of the root if (p.data > root.data && q.data > root.data) { return(findCommonAncestor(root.right, p, q)); } // p and q is right side of the root if (p.data < root.data && q.data < root.data) { return(findCommonAncestor(root.left, p, q)); } // if above both codition wrong then two are getting diversion at this root so return root. return(root); }
public static Bnode <int> ConstructBinaryTree(List <int> preOrder, List <int> inOrder) { Bnode <int> root = null; if (preOrder.Count != 0 && inOrder.Count != 0) { root = new Bnode <int>(preOrder[0]); int rootIdx = inOrder.IndexOf(root.data); //Left & Right SubTree inOrder List <int> leftSubTreeIn = inOrder.GetRange(0, rootIdx); List <int> rightSubTreeIn = inOrder.GetRange(rootIdx + 1, inOrder.Count - 1 - rootIdx); //left & right SubTree PreOrder int position = leftSubTreeIn.Count; List <int> leftSubTreePre = preOrder.GetRange(1, position); List <int> rightSubTreePre = preOrder.GetRange(position + 1, preOrder.Count - 1 - position); root.left = ConstructBinaryTree(leftSubTreePre, leftSubTreeIn); root.right = ConstructBinaryTree(rightSubTreePre, rightSubTreeIn); } return(root); }
public void InorderTraversalUsingStack(Bnode <int> node) { Stack <Bnode <int> > s = new Stack <Bnode <int> >(); while (node != null) { while (node != null) { if (node.right != null) { s.Push(node.right); } s.Push(node); node = node.left; } Bnode <int> p = s.Pop();// visit left child First while (p.right == null && s.Count != 0) { Console.WriteLine(p.data); //visit middle (root) node p = s.Pop(); } // you are visiting middle node any case // weather it has right child or not Console.WriteLine(p.data); //visit middle (root) node //if right child exist go for iteration if (s.Count != 0) { node = s.Pop(); // pop right child and now iterat again } else { node = null; } } }
//Tree1 is a big tree and Tree2 is a Sub Tree //Steps //1. For each Tree1 node // you check Tree2 is subTree ( identical ) //And Identical Tree means every node of Tree1 must match with every node of Tree2 // public Boolean FindSubTree(Bnode <int> Tree1, Bnode <int> Tree2) { //When traversing through Tree1 you never return with if (Tree1 == null) { return(false); } //if Tree2 is itself null means it is sub tree if (Tree2 == null) { return(true); } if (IsIdentical(Tree1, Tree2)) { return(true); } //if you don't find sub tree with Tree1's root, try left and Try right subTrees // one by one. return(FindSubTree(Tree1.left, Tree2) || FindSubTree(Tree1.right, Tree2)); }
//public Boolean IsBST(bnode<int> root) //{ // if (root == null) return true; // //left value in binary search tree is always less than the root // //So I am checking all the values in left sub binary tree of a root, // // and finding maximum value from left sub tree, and if I found that // // maximum value if found is greater than root value so not bst return false // //if (root.left != null && MaxValueFromSubTree(root.left) > root.data) // return false; // //if (root.right!=null && MinValueFromSubTree(root.right) < root.data) // //return false; //} //Ceil value = node with smallest data value which is larger or equal to key value // //if key value is grater that maxium value in BST than return null public int FindCeiling(Bnode <int> root, int key) { if (root == null) { return(-1); } //Case 1: you found key matches with some node data if (root.data == key) { return(root.data); } //case 2: if key is greater than root go to the right subtree, //probably you found ceiling value in right subtree if (root.data < key) { return(FindCeiling(root.right, key)); } // Case 3: Go to the left subtree becuase key is less value than root data, // so you find ceiling value in left subt tree //basically below statment says that you can find ceil value to the left subtree , //We may find a node with is larger data than key value in left subtree, //if not the root itself will be ceil node. int ceil = FindCeiling(root.left, key); if (ceil >= key) { return(ceil); } else { return(root.data); } }
public void printTreeVertically(Bnode <int> root) { var dict = new Dictionary <int, List <Bnode <int> > >(); GetVerticalOrder(root, 0, dict); var min = int.MaxValue; var max = int.MinValue; //get min hd distance ( left ) and max hd distance foreach (var k in dict.Keys) { if (k < min) { min = k; } if (k > max) { max = k; } } while (min < max) { if (dict.ContainsKey(min)) { var list = dict[min]; for (int i = 0; i < list.Count; i++) { Console.Write(list[i].data); } Console.WriteLine("\n"); } } }
public Boolean FindSumPath(Bnode <int> curNode, int sum) { //every time we substract current node with sum value // at the end sum == 0 then we found the sum path if (curNode == null && sum == 0) { return(true); } if (curNode == null) { return(false); } int subsum = sum - curNode.data; if (curNode.left == null && curNode.right == null && subsum == 0) { return(true); } return(FindSumPath(curNode.left, subsum) || FindSumPath(curNode.right, subsum)); }