public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { int first = (int)Math.Min (p.val, q.val); int second = (int)Math.Max(p.val, q.val); return LowestCommonAncestor (root, first, second); }
public static void Main(string[] args) { TreeNode n6 = new TreeNode (6); TreeNode n2 = new TreeNode (2); TreeNode n8 = new TreeNode (8); TreeNode n0 = new TreeNode (0); TreeNode n3 = new TreeNode (3); TreeNode n4 = new TreeNode (4); TreeNode n5 = new TreeNode (5); TreeNode n7 = new TreeNode (7); TreeNode n9 = new TreeNode (9); n6.left = n2; n6.right = n8; n2.left = n0; n2.right = n4; n4.left = n3; n4.right = n5; n8.left = n7; n8.right = n9; BstOp o = new BstOp (); // Console.WriteLine ("Result " + o.LowestCommonAncestor(n6,n2,n0).val); int[] arr = new int[]{ 2,3,1}; ArrayOps arrayOp = new ArrayOps(); Console.WriteLine (arrayOp.FindMin(arr)); }
public int KthSmallest(TreeNode root, int k) { int[] arr = new int[1]; int[] kArr = new int[1]; kArr [0] = k; KthSmallest (root, kArr, arr); return arr [0]; }
public void AddToBst(int num) { if (root == null) { root = new TreeNode (num); } else { var newNode = new TreeNode (num); AddToBst (root, newNode); } }
public void AddToBst(TreeNode root, TreeNode newNode) { if (root == null) { return; } if (root.val <= newNode.val) { if (root.right == null) { root.right = newNode; } else { AddToBst (root.right, newNode); } } else { if (root.left == null) { root.left = newNode; } else { AddToBst (root.left, newNode); } } }
public void KthSmallest(TreeNode root, int[] k,int[] arr) { if (root == null) { return ; } if (found) { return; } KthSmallest (root.left, k,arr); // Console.WriteLine (root.val); k [0] -= 1; if (k [0] == 0) { arr [0] = root.val; found = true; return; } KthSmallest (root.right, k,arr); }
public TreeNode LowestCommonAncestor(TreeNode root, int p, int q) { if (root == null) { return null; } Console.WriteLine (root.val); if (root.val <= q && root.val >= p) { return root; } var left = LowestCommonAncestor (root.left, p, q); if (left != null) { return left; } var right = LowestCommonAncestor (root.right,p,q); return right; }