public TreeNodeWithParent(int data) { Data = data; Left = null; Right = null; Parent = null; }
public static TreeNodeWithParent GetInOrderSuccessor(TreeNodeWithParent node) { if (node == null) { return(node); } if (node.RightNode != null) { return(GetLeftMostChild(node.LeftNode)); } else { TreeNodeWithParent q = node; TreeNodeWithParent x = q.ParentNode; //Go up until we're on left instead of right // We know that we change from left to root when the left is the same as q. while (x != null && x.LeftNode != q) { q = x; x = x.ParentNode; } return(x); } }
public static TreeNodeWithParent <int> LCA(TreeNodeWithParent <int> node0, TreeNodeWithParent <int> node1) { var n0Depth = GetDepth(node0); var n1Depth = GetDepth(node1); if (n1Depth > n0Depth) { var temp = node0; node0 = node1; node1 = temp; } var depthDiff = Math.Abs(n0Depth - n1Depth); while (depthDiff-- > 0) { node0 = node0.Parent; } while (node0 != node1) { node0 = node0.Parent; node1 = node1.Parent; } return(node0); }
static void Main(string[] args) { TreeNodeWithParent root = new TreeNodeWithParent(1); var node2 = new TreeNodeWithParent(2); var node3 = new TreeNodeWithParent(3); var node4 = new TreeNodeWithParent(4); var node5 = new TreeNodeWithParent(5); var node6 = new TreeNodeWithParent(6); var node7 = new TreeNodeWithParent(7); root.Left = node2; root.Right = node3; node2.Left = node4; node2.Right = node5; node2.Parent = root; node3.Left = node6; node3.Right = node7; node2.Parent = root; node4.Parent = node2; node5.Parent = node2; node6.Parent = node3; node7.Parent = node3; Console.Write(InOrderSuccessor(node2).Data); Console.ReadLine(); }
private static TreeNodeWithParent LeftMostChild(TreeNodeWithParent root) { TreeNodeWithParent current = root; while (current.Left != null) { current = current.Left; } return(current); }
private static int GetDepth(TreeNodeWithParent <int> node) { var depth = 0; while (node.Parent != null) { node = node.Parent; depth++; } return(depth); }
private static TreeNodeWithParent GetLeftMostChild(TreeNodeWithParent node) { if (node == null) { return(null); } while (node.LeftNode != null) { node = node.LeftNode; } return(node); }
private static TreeNodeWithParent InOrderSuccessor(TreeNodeWithParent node) { if (node == null) { return(null); } if (node.Right != null) { return(LeftMostChild(node.Right)); } else { TreeNodeWithParent child = node; TreeNodeWithParent parent = node.Parent; while (parent != null && parent.Left != child) { child = parent; parent = child.Parent; } return(parent); } }