Example #1
0
        public static Node BstFrmPostOrder(int[] postorder)
        {
            PostOrderIndex postOrderIndex = new PostOrderIndex();

            postOrderIndex.Index = postorder.Length - 1;
            return(BstFrmPostorder(postorder, Int32.MinValue, Int32.MaxValue, postOrderIndex));
        }
        public static Node BuildTree(int[] postorder, int[] inorder)
        {
            PostOrderIndex        postOrderIndex = new PostOrderIndex();
            Dictionary <int, int> inorderDict    = new Dictionary <int, int>();

            for (int i = 0; i < inorder.Length; i++)
            {
                inorderDict.Add(inorder[i], i);
            }

            postOrderIndex.Index = postorder.Length - 1;

            return(BuildTreeHelper(postorder, 0, postorder.Length - 1, postOrderIndex, inorderDict));
        }
        public static Node BuildTreeHelper(int[] postorder, int start, int end, PostOrderIndex postOrderIndex, Dictionary <int, int> inorderDict)
        {
            if (start > end)
            {
                return(null);
            }

            Node root = new Node(postorder[postOrderIndex.Index--]);

            int inorderIndex = inorderDict[root.Data];

            root.Right = BuildTreeHelper(postorder, inorderIndex + 1, end, postOrderIndex, inorderDict);
            root.Left  = BuildTreeHelper(postorder, start, inorderIndex - 1, postOrderIndex, inorderDict);
            return(root);
        }
Example #4
0
        public static Node BstFrmPostorder(int[] postorder, int min, int max, PostOrderIndex postOrderIndex)
        {
            if (postOrderIndex.Index < 0)
            {
                return(null);
            }
            if (postorder[postOrderIndex.Index] < min || postorder[postOrderIndex.Index] > max)
            {
                return(null);
            }
            // -- instead of ++
            Node root = new Node(postorder[postOrderIndex.Index--]);

            //right before left
            root.Right = BstFrmPostorder(postorder, root.Data, max, postOrderIndex);
            root.Left  = BstFrmPostorder(postorder, min, root.Data, postOrderIndex);


            return(root);
        }