zoukankan      html  css  js  c++  java
  • 剑指offer——重建二叉树

    重建二叉树

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

    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
            
        }
    }
    

      

    自己写的不对,在传入左右子树的范围那里  preLeft + i - inLeft  为什么不能直接是 i

    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
            TreeNode tree = subTree(pre, 0, pre.length - 1, in, 0, in.length - 1);
            return tree;
        }
        public TreeNode subTree(int[] pre, int preLeft, int preRight, int[] in, int inLeft, int inRight){
            if(preLeft > preRight || inLeft > inRight) return null;
    
            TreeNode subRoot = new TreeNode(pre[preLeft]);
            for(int i = 0; i < in.length; ++i){
                if(in[i] == pre[preLeft]){
                    subRoot.left = this.subTree(pre, preLeft + 1, preLeft + i - inLeft, in, inLeft, i - 1);
                    subRoot.right = this.subTree(pre, preLeft + i - inLeft + 1, preRight, in, i + 1, inRight);
                    break;
                }
            }
            return subRoot;
        }
    }
    

      

  • 相关阅读:
    操作符重载
    虚继承
    虚函数(2)
    基类与子类的成员函数的关系
    虚函数
    虚函数的简单应用
    齐国的粮食战
    纯虚函数
    类的继承(2)
    输出自定义日期格式
  • 原文地址:https://www.cnblogs.com/SkyeAngel/p/8530843.html
Copyright © 2011-2022 走看看