zoukankan      html  css  js  c++  java
  • 前序遍历 中序遍历树构造二叉树

    /**
    * Definition of TreeNode:
    * public class TreeNode {
    * public int val;
    * public TreeNode left, right;
    * public TreeNode(int val) {
    * this.val = val;
    * this.left = this.right = null;
    * }
    * }
    */
    public class Solution {
    /**
    *@param preorder : A list of integers that preorder traversal of a tree
    *@param inorder : A list of integers that inorder traversal of a tree
    *@return : Root of a tree
    */
    //找到根节点的位置
    private int findPosition(int[] array, int start, int end, int key) {
    for (int i = start; i <= end; i++) {
    if (array[i] == key) {
    return i;
    }
    }
    return -1;
    }
    private TreeNode myBuildTree(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart, int inEnd) {
    if (inStart > inEnd) {
    return null;
    }
    //前序遍历序列的第一个数字就是根结点,创建根结点root
    TreeNode root = new TreeNode(preorder[preStart]);
    //在中序遍历序列中找到根结点的位置
    int position = findPosition(inorder, inStart, inEnd, preorder[preStart]);
    //构建左子树
    root.left = myBuildTree(preorder, preStart + 1, preStart + (position - inStart), inorder, inStart, position - 1);
    //构建右子树
    root.right = myBuildTree(preorder, preStart + (position - inStart) + 1, preEnd, inorder, position + 1, inEnd);
    return root;
    }
    public TreeNode buildTree(int[] preorder, int[] inorder) {
    if (preorder.length != inorder.length) {//前序遍历序列与中序遍历序列长度不等
    return null;
    }
    return myBuildTree(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
    }
    }

  • 相关阅读:
    apollo使用场景2
    我问问
    洛谷 P3979 遥远的国度
    小技巧—对拍和输出文件的比较
    洛谷 P6850 NOI
    小技巧—双向边快速枚举
    ZJOI 2008 骑士
    小技巧—指数形式的枚举
    小技巧—滚动数组
    刷题心得—背包问题的枚举方式
  • 原文地址:https://www.cnblogs.com/mac10/p/7445360.html
Copyright © 2011-2022 走看看