劍指offer 二叉樹重構問題

來源:互聯網
上載者:User

輸入某二叉樹的前序走訪和中序遍曆的結果,請重建出該二叉樹。假設輸入的前序走訪和中序遍曆的結果中都不含重複的數字。例如輸入前序走訪序列{1,2,4,7,3,5,6,8}和中序遍曆序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。


java實現代碼:

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */import java.util.ArrayList;public class Solution {    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {        if(pre==null && in==null)            return null;       TreeNode root=new TreeNode(pre[0]);       int left_length=0;       int right_length=0;              for(int i=0;i<in.length;i++){           if(in[i]==pre[0]){               break;           }else{               left_length++;           }       }       right_length=in.length-left_length-1;                if(left_length!=0){            int prel[]=new int[left_length];            int inl[]=new int[left_length];           for(int i=0;i<left_length;i++){           prel[i]=pre[i+1];            inl[i]=in[i];           }           root.left=reConstructBinaryTree(prel,inl);         }        else{            root.left=null;        }               if(right_length!=0){           int prer[]=new int[right_length];           int inr[]=new int[right_length];           int count=0;           for(int i=right_length;i>0;i--){               prer[count]=pre[pre.length-i];               inr[count]=in[pre.length-i];               count++;           }           root.right=reConstructBinaryTree(prer,inr); ;         }        else{            root.right=null;        }                        return root;    }}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.