leetcode Construct Binary Tree from Inorder and Postorder Traversal

    xiaoxiao2025-10-26  5

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

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

    后序遍历的最后一个节点必为根节点,而中序遍历的根节点处的左半部分和右半部分必为左子树和右子树,根据这个性质递归即可,代码:

    public TreeNode buildTree(int[] inorder, int[] postorder) { if(inorder==null||inorder.length==0||postorder==null||postorder.length==0) return null; if(inorder.length==1) return new TreeNode(inorder[0]); TreeNode root=new TreeNode(postorder[postorder.length-1]); int index=0; for(int i=0;i<inorder.length;i++){ if(inorder[i]==root.val){ index=i; break; } } root.left=buildTree(Arrays.copyOfRange(inorder,0,index),Arrays.copyOfRange(postorder,0,index)); root.right=buildTree(Arrays.copyOfRange(inorder,index+1,postorder.length),Arrays.copyOfRange(postorder,index,postorder.length-1)); return root; }

    转载请注明原文地址: https://ju.6miu.com/read-1303529.html
    最新回复(0)