/// <summary> /// Algorithm that returns the next sequential node (ascending) when given a binary search tree node. Nodes in the tree have access to parent. /// O(n) time, O(1) space /// </summary> /// <param name="node">BSTPNode</param> /// <returns>BSTPNode</returns> public static BSTPNode Successor(BSTPNode node) { if (node == null) { return(null); } if (node.Right != null) { BSTPNode currChild = (BSTPNode)node.Right; while (currChild.Left != null) { currChild = (BSTPNode)currChild.Left; } return(currChild); } BSTPNode currParent = node.Parent; if (currParent == null) { return(null); } while (currParent != null && currParent.Data < node.Data) { currParent = currParent.Parent; } return(currParent); }
public void TestSuccessor() { // Arrange // null node BSTPNode nullNode = null; // single node BSTPNode singleNode = new BSTPNode(1, null); // common case BSTPNode commonCaseRoot = new BSTPNode(10, null); BSTPNode commonCaseLeft = new BSTPNode(7, commonCaseRoot); BSTPNode commonCaseLeftRight = new BSTPNode(9, commonCaseLeft); BSTPNode commonCaseLeftRightLeft = new BSTPNode(8, commonCaseLeftRight); BSTPNode commonCaseRight = new BSTPNode(11, commonCaseRoot); commonCaseRoot.Left = commonCaseLeft; commonCaseRoot.Right = commonCaseRight; commonCaseLeft.Right = commonCaseLeftRight; commonCaseLeftRight.Left = commonCaseLeftRightLeft; // Act BSTPNode nullNodeResult = TreesAndGraphs.Successor(nullNode); BSTPNode singleNodeResult = TreesAndGraphs.Successor(singleNode); BSTPNode commonCaseResult1 = TreesAndGraphs.Successor(commonCaseLeft); BSTPNode commonCaseResult2 = TreesAndGraphs.Successor(commonCaseLeftRight); BSTPNode commonCaseResult3 = TreesAndGraphs.Successor(commonCaseRight); // Assert Assert.IsNull(nullNodeResult); Assert.IsNull(singleNodeResult); Assert.AreEqual(commonCaseLeftRightLeft, commonCaseResult1); Assert.AreEqual(commonCaseRoot, commonCaseResult2); Assert.IsNull(commonCaseResult3); }
public BSTPNode(int data, BSTPNode parent) : base(data) { Parent = parent; }