題目1:二叉樹的深度
/** * 二叉樹的深度 * 輸入一棵二叉樹,求該樹的深度。從根結點到葉結點依次經過的結點(含根、葉結點) * 形成樹的一條路徑,最長路徑的長度爲樹的深度。 */
class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public static int TreeDepth(TreeNode root) {
if (root == null) {
return 0;
}
return 1 + Math.max(TreeDepth(root.right), TreeDepth(root.left));
}
題目2:不用加減乘除做加法
/**不用加減乘除做加法 * 寫一個函數,求兩個整數之和,要求在函數體內不得使用+、-、*、/四則運算符號。 * 在計組中,半加器、全加器中: * 兩個二進制的相加結果是用一個異或門實現的; * 兩個二進制的進位結果是用一個與門來實現的。 */
public static int Add(int num1,int num2) {
int res=0;
int jw=0;
do{
res=num1^num2;//每一位相加
jw=(num1&num2)<<1;//進位
num1=res;
num2=jw;
}while (jw!=0);
return res;
}
題目3:數組中重複的數字
/** * 數組中重複的數字 * 在一個長度爲n的數組裏的所有數字都在0到n-1的範圍內。 * 數組中某些數字是重複的,但不知道有幾個數字是重複的。 * 也不知道每個數字重複幾次。請找出數組中任意一個重複的數字。 * 例如,如果輸入長度爲7的數組{2,3,1,0,2,5,3}, * 那麼對應的輸出是第一個重複的數字2。 */
public boolean duplicate(int numbers[], int length, int[] duplication) {
boolean b = false;
if (numbers == null) {
b = false;
} else {
int[] re = new int[numbers.length];
for (int i = 0; i < numbers.length; i++) {
int a = numbers[i];
re[a] += 1;
if (re[a] > 1) {
b = true;
duplication[0] = a;
break;
}
}
}
if (!b) {
duplication[0] = -1;
}
return b;
}
題目4:重建二叉樹
/** * 重建二叉樹 * 輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。 * 假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。 * 例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6}, * 則重建二叉樹並返回。 */
public void build(TreeNode root, int[] pre, int pleft, int pright, int[] in, int ileft, int iright) {
int i;
for (i = ileft; i < iright; i++) {
if (in[i] == root.val) {
break;
}
}
int t = i - ileft;
if (t > 0) {
root.left = new TreeNode(pre[pleft + 1]);
build(root.left, pre, pleft + 1, pleft + 1 + t, in, ileft, i);
}
if (pright - pleft - 1 - t > 0) {
root.right = new TreeNode(pre[pleft + 1 + t]);
build(root.right, pre, pleft + 1 + t, pright, in, i + 1, iright);
}
}
題目5:旋轉數組中的最小數字
/** * 旋轉數組中的最小數字 * 題目描述 * 把一個數組最開始的若干個元素搬到數組的末尾,我們稱之爲數組的旋轉。 * 輸入一個非遞減排序的數組的一個旋轉,輸出旋轉數組的最小元素。 * 例如數組{3,4,5,1,2}爲{1,2,3,4,5}的一個旋轉,該數組的最小值爲1。 * NOTE:給出的所有元素都大於0,若數組大小爲0,請返回0。 */
public int minNum(int[] array) {
int l = 0;
int r = array.length - 1;
int mid;
int res = 0;
while (l < r) {
mid = l + (r - l) / 2;
if (array[l] >= array[r] && array[mid] > array[r]) {
l = mid +1;
} else if (array[l] >= array[r] && array[mid] <= array[r]) {
r = mid;
} if(array[l]<array[r]){
res=array[l];
break;
}
}
res = array[l];
return res;
}