zoukankan      html  css  js  c++  java
  • 递归重建二叉树的思路

    (1)通过前序列表(根左右)中序列表(左跟右)来重建二叉树
    思路 前序遍历 序列中,第一个数字总是二叉树的根节点。在中序遍历 序列中,根节点的值在序列的中间,左子树的节点的值位于根节点的值的左边,右子树的节点的值位于根节点的值的右边。根据二叉树的这个性质,采用递归方法可以重建一个二叉树了。

    /**
     * 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 node=reConstructBinaryTree(pre,0,pre.length-1,in,0,in.length-1);
            return node;
        }
        public TreeNode reConstructBinaryTree(int [] pre,int ps,int pe,int [] in,int is,int ie) {
            if(ps>pe)//如果开始位置大于结束位置说明已经处理到叶节点了
                return null;
            int value=pre[ps];
            int index=is;
            while(index<=ie&&in[index]!=value)//找到的index为根节点在中序遍历序列中的索引
                index++;
            TreeNode node=new TreeNode(pre[startPre]);
            node.left=reConstructBinaryTree(pre,ps+1,ps+index-is,in,is,index-1);
            node.right=reConstructBinaryTree(pre,ps+index-is+1,pe,in,index+1,ie);
            return node;
        }
    }

    (2)用Java中的Arrays.copyOfRange完成二叉树的重建工作

    Arrays.copyOfRange(T[ ] original,int from,int to)
    将一个原始的数组original,从小标from开始复制,复制到小标to,生成一个新的数组。
    注意这里包括下标from,不包括下标to。

     public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
            if(pre.length == 0 || in.length == 0){
                return null;
            }
            TreeNode node = new TreeNode(pre[0]);//获取根节点
            for(int i = 0 ; i < in.length ; i++){
                if(pre[0] == in[i]){
                    node.left = reConstructBinaryTree(Arrays.copyOfRange(pre, 1, i+1), Arrays.copyOfRange(in, 0, i));
                    node.right = reConstructBinaryTree(Arrays.copyOfRange(pre, i+1, pre.length), Arrays.copyOfRange(in, i+1, in.length));
                }
            }
            return node;
    
        }
    希望在知识中书写人生的代码
  • 相关阅读:
    因式分解
    插入排序算法
    小技巧(杂乱篇章)
    错误的模糊应用(类继承问题)
    同源策略和跨域解决方案
    Django admin源码剖析
    Python中该使用%还是format来格式化字符串?
    Django的认证系统
    Django中间件
    Django form表单
  • 原文地址:https://www.cnblogs.com/tongxupeng/p/10259557.html
Copyright © 2011-2022 走看看