public void Test2()
        {
            var root = new BinaryNodeWithParent()
            {
                Value = 10
            };

            root.Left = new BinaryNodeWithParent()
            {
                Value = 2, Parent = root
            };

            var fifteen = new BinaryNodeWithParent()
            {
                Value = 15, Parent = root
            };

            fifteen.Left = new BinaryNodeWithParent()
            {
                Value = 12, Parent = fifteen
            };
            fifteen.Right = new BinaryNodeWithParent()
            {
                Value = 18, Parent = fifteen
            };

            root.Right = fifteen;

            var nextInOrder = FindInOrderSuccessor.Find(fifteen.Left as BinaryNodeWithParent);

            Assert.That(nextInOrder.Value, Is.EqualTo(15));
        }
        public static BinaryNodeWithParent Find(BinaryNodeWithParent node)
        {
            if (node.Parent == null || node.Parent.Parent == null)
            {
                return(FindMaxLeft(node));
            }

            var gpa = node.Parent.Parent;

            if (gpa.Value < node.Parent.Value)
            {
                return(node.Parent);
            }

            return(gpa);
        }
Example #3
0
        public void Test2()
        {
            var root = new BinaryNodeWithParent()
            {
                Value = 1
            };
            var three = new BinaryNodeWithParent()
            {
                Value = 3, Parent = root
            };
            var two = new BinaryNodeWithParent()
            {
                Value = 2, Parent = root
            };

            var four = new BinaryNodeWithParent()
            {
                Value = 4, Parent = three
            };
            var six = new BinaryNodeWithParent()
            {
                Value = 6, Parent = three
            };
            var five = new BinaryNodeWithParent()
            {
                Value = 5, Parent = six
            };

            root.Left  = three;
            root.Right = two;

            three.Left  = four;
            three.Right = six;

            six.Left = five;

            var impl = new LcaImpl();
            var res  = impl.Lca(root, three, five);

            Assert.That(res.Value, Is.EqualTo(3));
        }
Example #4
0
        public BinaryNodeWithParent Lca(BinaryNodeWithParent root, BinaryNodeWithParent a, BinaryNodeWithParent b)
        {
            var pathFromA = new HashSet <BinaryNode>();
            var tmp       = a;

            while (tmp != null)
            {
                pathFromA.Add(tmp);
                tmp = tmp = tmp.Parent;
            }

            tmp = b;

            while (tmp != null)
            {
                if (pathFromA.Contains(tmp))
                {
                    return(tmp);
                }
                tmp = tmp.Parent;
            }

            return(null);
        }