java Tree

来源:互联网 发布:上瘾网络剧微博 编辑:程序博客网 时间:2024/06/05 17:44

最近做了好多在线笔试,发现关于树的问题还是很多的,在这里做一个统一整理

都是最基本的:

树的定义‘

public class Tree {Tree left;Tree right;int val;public Tree(int val){this.val=val;}}
建树

一种数组,一种前序中序建树 

public class BuildTree {public Tree createTree(Tree root,int[]nums,int i){int len=nums.length;root=new Tree(nums[i]);if(2*i+1<len)root.left=createTree(root.left,nums,2*i+1);if(2*i+2<len)root.right=createTree(root.right,nums,2*i+2);return root;}public Tree createTree(Tree root,int[]pre,int[]mid){root=new Tree(pre[0]);int index=getIndex(pre[0],mid);int[]prel=Arrays.copyOfRange(pre, 1,index+1);int[]midl=Arrays.copyOfRange(mid, 0,index);int[]prer=Arrays.copyOfRange(pre, index+1,pre.length);int[]midr=Arrays.copyOfRange(mid, index+1,mid.length);if(prel.length!=0) root.left=createTree(root.left,prel,midl);if(prer.length!=0) root.right=createTree(root.right,prer,midr);return root;}public int getIndex(int n,int[]num){for(int i=0;i<num.length;i++){if(n==num[i]) return i;}return -1;}}

树的遍历: 5种遍历 外加路径

import java.util.ArrayList;import java.util.Queue;import java.util.Stack;import java.util.concurrent.LinkedBlockingQueue;public class SearchTree {public void preSearch(Tree root){if(root==null) return;System.out.println(root.val);preSearch(root.left);preSearch(root.right);}public void midSearch(Tree root){if(root==null) return;preSearch(root.left);System.out.println(root.val);preSearch(root.right);}public void proSearch(Tree root){if(root==null) return;preSearch(root.left);preSearch(root.right);System.out.println(root.val);}public void pSearch(Tree root){if(root==null) return;Queue<Tree> res=new LinkedBlockingQueue<Tree>();res.add(root);while(!res.isEmpty()){Tree temp=res.poll();System.out.println(temp.val);if(temp.left!=null)res.add(temp.left);if(temp.right!=null) res.add(temp.right);}}public void dSearch(Tree root){if(root==null) return;Stack<Tree> res=new Stack<Tree>();res.add(root);while(!res.isEmpty()){Tree temp=res.pop();System.out.println(temp.val);if(temp.right!=null) res.add(temp.right);if(temp.left!=null)res.add(temp.left);}}    public ArrayList<ArrayList<Integer>> FindPath(Tree root,ArrayList<ArrayList<Integer>>res,ArrayList<Integer> mres) {        if(root==null) return res;        mres.add(root.val);;        if(root.left==null&&root.right==null) res.add(new ArrayList<Integer>(mres));        FindPath(root.left,res,mres);        FindPath(root.right,res,mres);        mres.remove(mres.size()-1);        return res;        }}


0 0
原创粉丝点击