二叉树完整练习

来源:互联网 发布:微型投影仪知乎 编辑:程序博客网 时间:2024/05/16 14:02
import java.util.ArrayList;import java.util.Iterator;import java.util.LinkedList;import java.util.List;import java.util.Queue;import java.util.Stack;class TreeNode{    TreeNode left;    TreeNode right;    int val;    public TreeNode(int val){        this.val = val;    }}public class TestForString {    static int total=0;    public static void main(String[] arg){        StringBuffer sb = new StringBuffer();        System.out.print(sb.length());    }    public static int getNodeNumRec(TreeNode root){        if(root == null){            return 0;        }else{            return getNodeNumRec(root.left)+getNodeNumRec(root.right)+1;        }    }    public static int getNodeNum(TreeNode root){        if(root == null){            return 0;        }        Queue<TreeNode> q = new LinkedList<TreeNode>();        q.offer(root);        int cnt = 0;        while(!q.isEmpty()){            TreeNode node = q.poll();            if(node.left!=null){                q.offer(node.left);            }            if(node.right!=null){                q.offer(node.right);            }            cnt++;        }        return cnt;    }    public static int getDepthRec(TreeNode root){        if(root==null){            return 0;        }else{            return 1+Math.max(getDepthRec(root.left), getDepthRec(root.right));        }    }    public static int getDepth(TreeNode root){        if(root==null){            return 0;        }        Queue<TreeNode> queue=new LinkedList<TreeNode>();        TreeNode dumy = new TreeNode(0);        queue.offer(root);        queue.offer(dumy);        int cnt=0;        while(!queue.isEmpty()){            TreeNode current = queue.poll();            if(current==dumy){                cnt++;                if(!queue.isEmpty()){                    queue.offer(dumy);                }            }            if(current.left!=null){                queue.offer(current.left);            }            if(current.right!=null){                queue.offer(current.right);            }        }        return cnt;    }    public static void preorderTraversalRec(TreeNode root){        if(root==null){            return;        }        System.out.print(root.val+" ");        preorderTraversalRec(root.left);        preorderTraversalRec(root.right);    }    public static void preorderTraversal(TreeNode root){        if(root == null){            return;        }        Stack<TreeNode> s = new Stack<TreeNode>();        s.push(root);        while(!s.isEmpty()){            TreeNode node = s.pop();            System.out.print(node.val+" ");            if(node.right!=null){                s.push(node.right);            }            if(node.left!=null){                s.push(node.left);            }        }    }    public static void inorderTraversalRec(TreeNode root){        if(root==null){            return;        }        inorderTraversalRec(root.left);        System.out.print(root.val+" ");        inorderTraversalRec(root.right);    }    public static void inorderTraversal(TreeNode root){        if(root==null){            return;        }        Stack<TreeNode> stack = new Stack<TreeNode>();        TreeNode current = root;        while(true){            while(current!=null){                stack.push(current);                current=current.left;            }            if(!stack.isEmpty()){                break;            }            current = stack.pop();            System.out.print(current.val+" ");            current = current.right;        }    }    public static void postorderTraversalRec(TreeNode root){        if(root==null){            return;        }        postorderTraversalRec(root.left);        postorderTraversalRec(root.right);        System.out.print(root.val+" ");    }    public static void postorderTraversal(TreeNode root){        if(root==null){            return;        }        Stack<TreeNode> stackIn = new Stack<TreeNode>();        Stack<TreeNode> stackOut = new Stack<TreeNode>();        stackIn.push(root);        while(!stackIn.isEmpty()){            TreeNode current = stackIn.pop();            stackOut.push(current);            if(current.left!=null){                stackIn.push(current.left);            }            if(current.right!=null){                stackIn.push(current.right);            }        }        while(!stackOut.isEmpty()){            System.out.print(stackOut.pop().val+" ");        }    }    public static void levelTraversalRec(TreeNode root){        ArrayList<ArrayList<Integer>>ret = new ArrayList<ArrayList<Integer>>();        levelTraversalVisit(root,0,ret);        System.out.print(ret);    }    private static void levelTraversalVisit(TreeNode root, int level,            ArrayList<ArrayList<Integer>> ret) {        if(root==null){            return;        }        if(level>=ret.size()){            ret.add(new ArrayList<Integer>());        }        ret.get(level).add(root.val);        levelTraversalVisit(root.left,level+1,ret);        levelTraversalVisit(root.right,level+1,ret);    }    public static void levelTraversalVisit(TreeNode root){        if(root==null){            return;        }        Queue<TreeNode> queue = new LinkedList<TreeNode>();        queue.offer(root);        while(!queue.isEmpty()){            TreeNode current  = queue.poll();            System.out.print(current.val+" ");            if(current.left!=null){                queue.offer(current.left);            }            if(current.right!=null){                queue.offer(current.right);            }        }    }    public static TreeNode convertBST2DLLRec(TreeNode root){        return converBST2DLLRecHelp(root)[0];    }    public static TreeNode[] converBST2DLLRecHelp(TreeNode root) {        TreeNode[] ret = new TreeNode[2];        //ret[0]表示由这个节点以及他的所有的子节点所创建的链表的做端点;        //ret[1]表示整个链表的右边的第一个节点,也就是链表的右边头部节点        ret[0]=null;        ret[1]=null;        if(root==null){            return ret;        }        if(root.right!=null){            TreeNode[] right=converBST2DLLRecHelp(root.right);            right[0].left=root;            root.right=right[0];            ret[1]=right[1];        }else{            ret[1]=root;        }        if(root.left!=null){            TreeNode[] left=converBST2DLLRecHelp(root.left);            left[1].right=root;            root.left=left[1];            ret[0]=left[0];        }else{            ret[0]=root;        }        return ret;    }    public static TreeNode convertBST2DLL(TreeNode root){        while(root==null){            return null;        }        Stack<TreeNode> stack = new Stack<TreeNode>();        TreeNode head = null;        TreeNode current = root;        TreeNode pre = null;        while(true){            while(current!=null){                stack.push(current);                current = current.left;            }            if(stack.isEmpty()){                break;            }            current = stack.pop();            if(head==null){                head=current;            }            current.left = pre;            if(pre!=null){                pre.right=current;            }            pre=current;            current = current.right;        }        return head;    }    public static int getNodeNumKthLevel(TreeNode root,int k){        if(root==null||k<=0){            return 0;        }        int level=0;        int count=0;        Queue<TreeNode> queue = new LinkedList<TreeNode>();        TreeNode current = root;        TreeNode dummy = new TreeNode(0);        queue.offer(current);        queue.offer(dummy);        while(!queue.isEmpty()){            current = queue.poll();            if(current==dummy){                level++;                if(level==k){                    return count;                }else{                    count=0;                    if(queue.isEmpty()){                        return count;                    }                    queue.offer(dummy);                }            }else{                count++;                if(current.left!=null){                    queue.offer(current.left);                }                if(current.right!=null){                    queue.offer(current.right);                }            }        }        return 0;    }    public static int getNodeNumKthLevelRec(TreeNode root,int k){        if(root==null){            return 0;        }        if(k==1){            return 1;        }        //根树的第K层其实就是左右子树的第K-1层,因为子树要比跟往下走一层;        return getNodeNumKthLevelRec(root.left,k-1)                +getNodeNumKthLevelRec(root.right,k-1);    }    public static int getNodeNumLeaf(TreeNode root){        if(root==null){return 0;}        int count=0;        TreeNode current = root;        Stack<TreeNode> stack = new Stack<TreeNode>();        while(true){            while(current!=null){                stack.push(current);                current=current.left;            }            if(stack.isEmpty()){                break;            }            current = stack.pop();            if(current.left==null&&current.right==null){                count++;            }            current=current.right;        }        return count;    }    public static int getNodeNumLeafRec(TreeNode root){        if(root==null){            return 0;        }        if(root.left==null&&root.right==null){            return 1;        }        return getNodeNumLeafRec(root.left)+getNodeNumLeafRec(root.right);    }    public static boolean isSameRec(TreeNode root1,TreeNode root2){        if(root1==null&&root2==null){            return true;        }        if(root1==null||root2==null){            return false;        }        return root1.val==root2.val&&                isSameRec(root1.left,root2.left)&&                isSameRec(root1.right,root2.right);    }    public static boolean isSame(TreeNode root1,TreeNode root2){        Stack<TreeNode> stack1 = new Stack<TreeNode>();        Stack<TreeNode> stack2 = new Stack<TreeNode>();        TreeNode current1 = root1;        TreeNode current2 = root2;        while(true){            while(current1!=null&&current2!=null){                stack1.push(current1);                current1=current1.left;                stack2.push(current2);                current2=current2.left;            }            if(current1!=null||current2!=null){                return false;            }            if(stack1.isEmpty()&&stack2.isEmpty()){                break;            }            current1=stack1.pop();            current2=stack2.pop();            if(current1.val!=current2.val){                return false;            }            current1=current1.right;            current2=current2.right;        }        return true;    }    public static boolean isAVLRec(TreeNode root){        if(root==null){            return true;        }        if(!isAVLRec(root.left)||!isAVLRec(root.right)){            return false;        }        int dif =  Math.abs(getDepthRec(root.left)-getDepthRec(root.right));        if(dif>1){            return false;        }        return true;    }    public static TreeNode mirrorRec(TreeNode root){        if(root==null){            return null;        }        TreeNode right = root.right;        root.right = mirrorRec(root.left);        root.left = mirrorRec(right);        return root;    }    public static TreeNode mirror(TreeNode root){        if(root==null){            return null;        }        Stack<TreeNode> stack = new Stack<TreeNode>();        TreeNode current = root;        stack.push(current);        while(!stack.isEmpty()){            current = stack.pop();            TreeNode right = current.right;            current.right = current.left;            current.left = right;            if(current.right!=null){                stack.push(current.right);            }            if(current.left!=null){                stack.push(current.left);            }        }        return root;    }    public static TreeNode mirrorCopy(TreeNode root){        if(root==null){            return null;        }        TreeNode rootCopy = new TreeNode(root.val);        TreeNode currentCopy = rootCopy;        Stack<TreeNode> stackCopy = new Stack<TreeNode>();        stackCopy.push(currentCopy);        Stack<TreeNode> stack = new Stack<TreeNode>();        TreeNode current = root;        stack.push(current);        while(!stack.isEmpty()){            current = stack.pop();            currentCopy = stack.pop();            TreeNode copyLeft = null;            TreeNode copyRight = null;            if(current.right!=null){                copyLeft = new TreeNode(current.right.val);                currentCopy.left=copyLeft;                stackCopy.push(currentCopy.left);                stack.push(current.right);            }            if(current.left!=null){                copyRight = new TreeNode(current.left.val);                currentCopy.right = copyRight;                stackCopy.push(currentCopy.right);                stack.push(current.left);               }        }        return rootCopy;    }    public static TreeNode mirrorCopyRec(TreeNode root){        if(root==null){            return null;        }        TreeNode copyRoot = new TreeNode(root.val);        copyRoot.left = mirrorCopyRec(root.right);        copyRoot.right = mirrorCopyRec(root.left);        return root;    }    public static boolean isMirrorRec(TreeNode root1,TreeNode root2){        if(root1==null&&root2==null){            return true;        }        if(root1==null||root2==null){            return false;        }        return root1.val==root2.val                &&isMirrorRec(root1.left,root2.right)                &&isMirrorRec(root1.right,root2.left);    }    public static boolean isMirror(TreeNode root1,TreeNode root2){        if(root1==null&&root2==null){            return true;        }        if(root1==null||root2==null){            return true;        }        TreeNode current1 = root1;        TreeNode current2 = root2;        Stack<TreeNode> stack1 = new Stack<TreeNode>();        Stack<TreeNode> stack2 = new Stack<TreeNode>();        while(!stack1.isEmpty()&&!stack2.isEmpty()){            current1 = stack1.pop();            current2 = stack2.pop();            if(current1.val!=current2.val){                return false;            }             if((current1.left==null&&current2.right!=null)                    ||(current1.left!=null||current2.right==null)){                return false;            }            if(current1.left!=null&&current2.right!=null){                stack1.push(current1.left);                stack2.push(current2.right);            }            if((current1.right==null&&current2.left!=null)                    ||(current1.right!=null&&current2.left==null)){                return false;               }            if(current1.right!=null&&current2.left!=null){                stack1.push(current1.right);                stack2.push(current2.left);            }        }        return true;    }    public static TreeNode LACRec(TreeNode root,TreeNode node1,TreeNode node2){        if(root==null||node1==null||node2==null){            return null;        }        if(root==node1||root==node2){            return root;        }        TreeNode  left = LACRec(root.left,node1,node2);        TreeNode  right= LACRec(root.right,node1,node2);        if(left==null){            return right;        }        if(right==null){            return left;        }        return root;    }    public static TreeNode LACBstRec(TreeNode root,TreeNode node1,TreeNode node2){        if(root==null||node1==null||node2==null){            return null;        }        if(root.val==node1.val||root.val==node2.val){            return root;        }        int max =Math.max(node1.val, node2.val);        int min =Math.max(node1.val, node2.val);        if(root.val<min){            return LACBstRec(root.right,node1,node2);        }        if(root.val>max){            return LACBstRec(root.left,node1,node2);        }        return root;    }    public static boolean LCAPath(TreeNode root,TreeNode node,ArrayList<TreeNode> path){        if(root==null||node==null){            return false;        }        path.add(root);        if(root.val!=node.val                &&!LCAPath(root.left,node,path)                &&LCAPath(root.right,node,path)){            path.remove(root);            return false;        }        return true;    }    /*     * 二叉树找寻最低公共节点     *      * */    public static TreeNode LCA(TreeNode root,TreeNode node1,TreeNode node2){        if(root==null||node1==null||node2==null){            return null;        }        ArrayList<TreeNode> path1 = new ArrayList<TreeNode>();        ArrayList<TreeNode> path2 = new ArrayList<TreeNode>();        boolean find1 = LCAPath(root,node1,path1);        boolean find2 = LCAPath(root,node2,path2);        if(!(find1&&find2)){            return null;        }        Iterator<TreeNode> iter1 = path1.iterator();        Iterator<TreeNode> iter2 = path2.iterator();        TreeNode last = null;        TreeNode nextNode1;        TreeNode nextNode2;        while(iter1.hasNext()&&iter2.hasNext()){            nextNode1=iter1.next();            nextNode2=iter2.next();            if(nextNode1==nextNode2){                last = nextNode1;            }else{                return last;            }        }        return last;    }    public static int getMaxDistanceRec(TreeNode root){        return getMaxDistanceRecHelp(root).maxDistance;    }    public static Result getMaxDistanceRecHelp(TreeNode root){        Result ret = new Result(-1,-1);        if(root==null){            return ret;        }        Result left = getMaxDistanceRecHelp(root.left);        Result right = getMaxDistanceRecHelp(root.right);        ret.depth = Math.max(left.depth,right.depth)+1;        int crossLen = left.depth + right.depth +2;        ret.maxDistance = Math.max(left.maxDistance, right.maxDistance);        ret.maxDistance = Math.max(crossLen, ret.maxDistance);        return ret;    }    private static class Result{        int depth;        int maxDistance;        public Result(int depth,int maxDistance){            this.depth = depth;            this.maxDistance = maxDistance;        }    }    public static TreeNode rebuildBinaryTreeRec(List<Integer> preOrder,List<Integer>inOrder){        if(preOrder==null||inOrder==null){            return null;        }        int rootVal = preOrder.get(0);        int rootIndex = inOrder.indexOf(rootVal);        if(rootIndex<0){            return null;        }        TreeNode root = new TreeNode(rootVal);        List<Integer> inOrderLeftTree =                 inOrder.subList(0, rootIndex);        List<Integer> inOrderRightTree =                 inOrder.subList(rootIndex+1, inOrder.size());        List<Integer> preOrderLeftTree =                 preOrder.subList(1, inOrderLeftTree.size()-1);        List<Integer> preOrderRightTree =                 preOrder.subList(preOrderLeftTree.size()+1, preOrder.size());        root.left = rebuildBinaryTreeRec(preOrderLeftTree,inOrderLeftTree);        root.right = rebuildBinaryTreeRec(preOrderRightTree,inOrderRightTree);        return root;    }    public static boolean isCompleteBinaryTree(TreeNode root){        if(root==null){            return false;        }        Queue<TreeNode> queue=new LinkedList<TreeNode>();        TreeNode dummy = new TreeNode(0);        TreeNode current = root;        queue.offer(current);        queue.offer(dummy);        boolean noChild = false;        while(!queue.isEmpty()){            current = queue.poll();            if(current==dummy){                if(queue.isEmpty()){                    break;                }                queue.offer(dummy);            }            if(current.left!=null){                if(noChild){                    return false;                }                queue.offer(current.left);            }else{                noChild = true;            }            if(current.right!=null){                if(noChild){                    return false;                }                queue.offer(current.right);            }else{                noChild = true;            }        }        return true;    }    private static class ReturnBinaryTree{        boolean isCompleteBT;        boolean isPerfectBT;        int height;        ReturnBinaryTree(boolean isCompleteBT,boolean isPerfectBT,int height){            this.isCompleteBT = isCompleteBT;            this.isPerfectBT = isPerfectBT;            this.height = height;        }    }    public static ReturnBinaryTree isCompleteBinaryTreeRecHelp(TreeNode root){        ReturnBinaryTree ret = new ReturnBinaryTree(true,true,-1);        if(root==null){            return ret;        }        ReturnBinaryTree leftRet = isCompleteBinaryTreeRecHelp(root.left);        ReturnBinaryTree rightRet = isCompleteBinaryTreeRecHelp(root.right);        ret.height = Math.max(leftRet.height,rightRet.height)+1;        ret.isPerfectBT=leftRet.isPerfectBT                &&rightRet.isPerfectBT&&leftRet.height==rightRet.height;        ret.isCompleteBT = ret.isPerfectBT                ||(leftRet.isCompleteBT&&rightRet.isPerfectBT&&leftRet.height==rightRet.height+1)                ||(leftRet.isPerfectBT&&rightRet.isCompleteBT&&leftRet.height==rightRet.height);        return ret;    }    public static int findLongest(TreeNode root){        if(root==null){            return -1;        }        int countLeft = 0;        TreeNode left=root;        if(left.left!=null){            countLeft++;            left=left.left;        }        int countRight=0;        TreeNode right=root;        if(right.right!=null){            countRight++;            right=right.right;        }        int longest = Math.max(findLongest(root.left), findLongest(root.right));        longest = Math.max(longest, countRight);        longest = Math.max(longest, countLeft);        return longest;    }}
0 0
原创粉丝点击