Exemple #1
0
        public static TreeBinaryParentNode <T> commonAncestor(TreeBinaryParentNode <T> firstNode, TreeBinaryParentNode <T> secondNode)
        {
            if (firstNode == null || secondNode == null)
            {
                throw new ArgumentNullException(message: "The nodes cannot be null", paramName: $"{nameof(firstNode)} or {nameof(secondNode)}");
            }

            int diff = getDepth(firstNode) - getDepth(secondNode);
            TreeBinaryParentNode <T> deepNode    = diff > 0 ? firstNode : secondNode;
            TreeBinaryParentNode <T> swallowNode = diff > 0 ? secondNode : firstNode;

            deepNode = goingUp(deepNode, Math.Abs(diff));

            if (deepNode == swallowNode)
            {
                return(swallowNode);
            }

            while (swallowNode != null && deepNode != swallowNode)
            {
                deepNode    = deepNode.parent;
                swallowNode = swallowNode.parent;
            }

            return((swallowNode == null) ? null : swallowNode);
        }
Exemple #2
0
        private static TreeBinaryParentNode <T> goingUp(TreeBinaryParentNode <T> node, int diff)
        {
            while (diff > 0)
            {
                node = node.parent;
                diff--;
            }

            return(node);
        }
Exemple #3
0
        private static int getDepth(TreeBinaryParentNode <T> node)
        {
            int depth = 0;

            while (node.parent != null)
            {
                node = node.parent;
                depth++;
            }

            return(depth);
        }
            private static TreeBinaryParentNode <T> MinimalParentTree <T>(T[] array, int start, int end, TreeBinaryParentNode <T> parent)
            {
                TreeBinaryParentNode <T> currentParent = parent;

                if (start > end)
                {
                    return(null);
                }

                int midIndex = (start + end) / 2;
                T   middle   = array[midIndex];

                parent       = new TreeBinaryParentNode <T>(middle, null, null, currentParent);
                parent.left  = MinimalParentTree <T>(array, start, midIndex - 1, parent);
                parent.right = MinimalParentTree <T>(array, midIndex + 1, end, parent);

                return(parent);
            }