题目:

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

思路:

递归,根节点是postorder的最后一个节点

package treetraversal;

public class ConstructBinaryTreeFromInorderAndPostorderTraversal {

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        return construct(postorder, 0, postorder.length - 1, inorder, 0, inorder.length - 1);
    }
    
    private TreeNode construct(int[] postorder, int pstart, int pend, int[] inorder, int istart, int iend) {
        if (pstart > pend || istart > iend) return null;
        int rootVal = postorder[pend];
        int index = -1;
        for (int i = istart; i <= iend; ++i) {
            if (inorder[i] == rootVal) {
                index = i;
                break;
            }
        }
        
        TreeNode root = new TreeNode(rootVal);        
        root.left = construct(postorder, pstart, pstart + index - istart - 1, inorder, istart, index - 1);
        root.right = construct(postorder, pstart + index - istart, pend - 1, inorder, index + 1, iend);
        return root;
    }
    
}

 

相关文章:

  • 2021-09-28
  • 2021-08-28
  • 2022-12-23
  • 2022-12-23
  • 2022-02-25
  • 2021-09-16
猜你喜欢
  • 2022-01-23
  • 2021-08-30
  • 2021-11-20
  • 2021-10-24
  • 2021-09-29
  • 2022-01-17
相关资源
相似解决方案