剑指offer——(8)重建二叉树&&二叉树的深度

版权声明:本文自由转载,转载请注明出处。 https://blog.csdn.net/qq_38071429/article/details/83894323

/**
 * 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) {         
        return searchTree(0,pre.length-1,0,in.length-1,pre,in);
    }
    
    TreeNode searchTree(int preS,int preE,int inS,int inE,int [] pre,int [] in){
        TreeNode result = new TreeNode(pre[preS]); 
        //result.val = pre[0];
        int temp = inS;
        for(;temp<=inE;temp++) if(in[temp]==pre[preS]) break;
        if(temp>inS) result.left = searchTree(preS+1,preS+temp-inS,inS,temp-1,pre,in);
        else result.left = null;
        if(temp<inE) result.right = searchTree(preS+temp-inS+1,preE,temp+1,inE,pre,in);
        else result.right = null;
        return result;
    }
}

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    //分别用两个变量存储递归 左孩子和右孩子的深度 最后比较两者大小
    int countL = 1,countR = 1,count = 0;
    public int TreeDepth(TreeNode root) {      
    	//根节点为空 树不存在返回0
        if(root==null) return 0;
        //只有根节点
        else if(root.left == null&&root.right == null) return 1;
        //有左孩子没有右孩子
        else if(root.left != null&&root.right == null){
        	countL++;
        	TreeDepth(root.left);                
        } 
        //有右孩子没有左孩子
        else if(root.left == null&&root.right != null){
        	countR++;
        	TreeDepth(root.right);       
        }     
        //同时有左、右孩子
        else {
        	countL++;
        	TreeDepth(root.left);      
        	countR++;
        	TreeDepth(root.right);       
        }
        return count = countL>countR?countL:countR;
    }
}
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public int TreeDepth(TreeNode root) {       
       if(root==null) return 0;
       return 1+TreeDepth(root.left)>1+TreeDepth(root.right)?1+TreeDepth(root.left):1+TreeDepth(root.right);
    }
}
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/

public class Solution {
    public int TreeDepth(TreeNode pRoot) {     
        if(pRoot == null)    
            return 0;       
        if(pRoot.left == null && pRoot.right == null)     
            return 1;       
        int left = TreeDepth(pRoot.left);   
        int right = TreeDepth(pRoot.right); 
        return left > right ? left + 1 : right + 1;    
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38071429/article/details/83894323
今日推荐