美文网首页
LeetCode-105-从前序与中序遍历序列构造二叉树

LeetCode-105-从前序与中序遍历序列构造二叉树

作者: 醉舞经阁半卷书 | 来源:发表于2021-11-13 08:01 被阅读0次

    从前序与中序遍历序列构造二叉树

    题目描述:给定一棵树的前序遍历 preorder 与中序遍历 inorder。请构造二叉树并返回其根节点。

    示例说明请见LeetCode官网。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    解法一:递归法

    通过递归的方式构造二叉树,递归过程如下:

    • 如果前序遍历序列或者中序遍历序列为空时,直接返回空树;
    • 因为前序遍历序列的第一个值为根节点,所以首先得到根节点;
    • 然后根据中序遍历中根节点的位置得到根节点的左右子树的节点的数量leftCount和rightCount;
    • 然后递归调用该方法得到当前根节点的左右子树;
    • 最后返回根节点。
    import com.kaesar.leetcode.TreeNode;
    
    import java.util.Arrays;
    
    public class LeetCode_105 {
        public static TreeNode buildTree(int[] preorder, int[] inorder) {
            // 当前序遍历序列或者中序遍历序列为空时,直接返回空树
            if (preorder == null || preorder.length == 0) {
                return null;
            }
            // 前序遍历序列的第一个值为根节点
            TreeNode root = new TreeNode(preorder[0]);
            // 左子树节点的数量
            int leftCount;
            // 中序遍历序列中,根节点左边的节点都是根节点左子树的节点
            for (leftCount = 0; leftCount < inorder.length; leftCount++) {
                if (inorder[leftCount] == preorder[0]) {
                    break;
                }
            }
            // 根据左子树节点数和总的节点数计算右子树节点的数量
            int rightCount = inorder.length - 1 - leftCount;
    
            // 递归调用得到当前节点的左右子树
            root.left = buildTree(Arrays.copyOfRange(preorder, 1, leftCount + 1), Arrays.copyOfRange(inorder, 0, leftCount));
            root.right = buildTree(Arrays.copyOfRange(preorder, leftCount + 1, preorder.length), Arrays.copyOfRange(inorder, leftCount + 1, inorder.length));
            return root;
        }
    
        public static void main(String[] args) {
            int[] preorder = new int[]{3, 9, 20, 15, 7};
            int[] inorder = new int[]{9, 3, 15, 20, 7};
            buildTree(preorder, inorder).print();
        }
    }
    

    【每日寄语】 我的生活从艰辛到自如没有强大的内心不可为之。无人能一手成就谁,真正的神在我心中。唯有自己努力方能见到曙光!

    相关文章

      网友评论

          本文标题:LeetCode-105-从前序与中序遍历序列构造二叉树

          本文链接:https://www.haomeiwen.com/subject/eymazltx.html