Binary tree from Preorder and inorder traversal

后端 未结 3 1856
小蘑菇
小蘑菇 2021-01-07 05:37

How can I get the tree form these pre/in order traversal:

Pre: A,B,D,E,C,F,G,H in:E,D,B,A,G,F,H,C

EDITED: MY Answer

       A         


        
3条回答
  •  终归单人心
    2021-01-07 06:30

    Below is a working implementation in C#

    public static class TreeUtil
    {
       public static BinarySearchTree FromTraversals(T[] preorder, T[] inorder)
       {
           if (preorder == null) throw new ArgumentNullException("preorder");
           if (inorder == null) throw new ArgumentNullException("inorder");
           if (preorder.Length != inorder.Length) throw new ArgumentException("inorder and preorder have different lengths");
    
           int n = preorder.Length;
           return new BinarySearchTree(FromTraversals(preorder, 0, n - 1, inorder, 0, n - 1));
       }
    
       public static BinaryTreeNode FromTraversals(T[] preorder, int pstart, int pend, T[] inorder, int istart, int iend)
       {
           if (pstart > pend) return null;
    
           T rootVal = preorder[pstart];
           int rootInPos;
           for (rootInPos = istart; rootInPos <= iend; rootInPos++) //find rootVal in inorder
               if (Comparer.Default.Compare(inorder[rootInPos], rootVal) == 0) break;
    
           if (rootInPos > iend)
               throw new ArgumentException("invalid inorder and preorder inputs");
    
           int offset = rootInPos - istart;
           return new BinaryTreeNode(rootVal)
               {
                   Left = FromTraversals(preorder, pstart + 1, pstart + offset, inorder, istart, istart + offset - 1),
                   Right = FromTraversals(preorder, pstart + offset + 1, pend, inorder, istart + offset + 1, iend),
               };
       }
    }
    

    Here is one possible implementation of BinarySearchTree and BinaryTreeNode. Some tests:

    [TestMethod]
    public void TestGenerationFromTraversals()
    {
      var preorder = new[] {1, 2, 4, 5, 3};
      var inorder = new[] {4, 2, 5, 1, 3};
      AssertGenerationFromTraversal(preorder, inorder);
    
      var preorder2 = new[] { 'A', 'B', 'D', 'E', 'C', 'F' };
      var inorder2 = new[] { 'D', 'B', 'E', 'A', 'F', 'C' };
      AssertGenerationFromTraversal(preorder2, inorder2);
    }
    
    private static void AssertGenerationFromTraversal(T[] preorder, T[] inorder)
    {
      var tree = BinarySearchTreeUtil.FromTraversals(preorder, inorder);
    
      var treeInorder = new List();
      tree.TraverseInOrder(treeInorder.Add);
      var treePre = new List();
      tree.TraversePreOrder(treePre.Add);
    
      Assert.IsTrue(preorder.SequenceEqual(treePre));
      Assert.IsTrue(inorder.SequenceEqual(treeInorder));
    }
    

提交回复
热议问题