• 剑指Offer_04_重建二叉树


    题目描述

    输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

    解题思路

    首先根据中序和前序遍历的特点,找出跟结点,然后根据根节点将数组划分成两段,一个是根结点的左子树,一个是根结点的右子树。然后递归调用,直至完成。

    实现

    /*树结点的定义*/
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }
    /*实现*/
    public class Solution {
        public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
            if (pre == null || in == null || pre.length != in.length || pre.length <=0) return null;
            return bulidTree(pre, 0, pre.length - 1, in, 0, in.length - 1);
        }
    
        private TreeNode bulidTree(int[] pre, int pStart, int pEnd, int[] in, int inStart, int inEnd) {
            if (pStart > pEnd || inStart > inEnd) return null;
            //找到根结点
            int rootVal = pre[pStart];
            TreeNode root = new TreeNode(rootVal);
            //在中序遍历中找到根结点的位置
            int rootIndex = inStart;
            for (int i = inStart; i <= inEnd; i++){
                if (in[i] == rootVal) rootIndex = i;
            }
    
            root.left = bulidTree(pre, pStart + 1, pStart + rootIndex - inStart, in, inStart, rootIndex - 1);
            root.right = bulidTree(pre, pStart + rootIndex - inStart + 1, pEnd, in, rootIndex + 1, inEnd);
    
            return root;
        }
    }
    
  • 相关阅读:
    CREATE VIEW
    CREATE USER
    安全层次
    PHP json_decode 函数解析 json 结果为 NULL 的解决方法
    Java实现 LeetCode 7整数反转
    Java实现 LeetCode 6 Z字形变换
    Java实现 LeetCode 6 Z字形变换
    Java实现 LeetCode 6 Z字形变换
    Java实现 LeetCode 5 最长回文子串
    Java实现 LeetCode 5 最长回文子串
  • 原文地址:https://www.cnblogs.com/ggmfengyangdi/p/5763578.html
Copyright © 2020-2023  润新知