劍指offer——(8)重建二叉樹&&二叉樹的深度
阿新 • • 發佈:2018-11-30
/** * 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;
}
}