# LintCode/LeetCode训练题目&答案详解—基础篇

``````     1
/   \
-5     2
/ \   /  \
0   3 -4  -5
``````

``````public class Solution {
/**
* @param root the root of binary tree
* @return the max node
*/
public TreeNode maxNode(TreeNode root) {
if (root == null) {
return null;
}
return getMaxTreeNode(root);
}

private TreeNode getMaxTreeNode(TreeNode root) {
if (root == null) {
return new TreeNode(Integer.MIN_VALUE);
}
TreeNode left = getMaxTreeNode(root.left);
TreeNode right = getMaxTreeNode(root.right);
if (root.val > left.val && root.val > right.val) {
return root;
} else if (right.val > left.val && right.val > root.val) {
return right;
}
return left;
}
}
``````

A a = A.getInstance();
A b = A.getInstance();
a 应等于 b.

``````class Solution {
private volatile static  Solution mInstance = null;
/**
* @return: The same instance of this class every time
*/
public static Solution getInstance() {
if (mInstance == null) {
synchronized(Solution.class) {
if (mInstance == null) {
mInstance = new Solution();
}
}
}
return mInstance;
}

private Solution() {}
``````

}

``````public void sortIntegers(int[] A) {
int i, j, min, temp, len = A.length;
for (i = 0; i < len -1; i++) {
min = i; //未排序序列中最小数据数组下标
for (j = i + 1; j < len; j++) { //在未排序元素中继续寻找最小元素，并保存其下标
if (A[min] > A[j]) {
min = j;
}
}
if (i != min) { //将最小元素放到已排序序列的末尾
temp = A[min];
A[min] = A[i];
A[i] = temp;
}
}
}
``````

``````public void sortIntegers(int[] A) {
int i, j, temp, len = A.length;
for (i = 0; i < len - 1; i++) {
for (j = 0; j < len - i - 1; j ++)
if (A[j] > A[j+1]) {
temp = A[j+1];
A[j+1] = A[j];
A[j] = temp;
}
}

}
``````

** 四、斐波那契数列**

0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...

``````public int fibonacci(int n) {
int a1 = 0;
int a2 = 1;
int result = 0;
if (n == 1) {
return a1;
}
if (n == 2) {
return a2;
}
for (int i = 3; i <= n; i++) {
result = a1 + a2;
a1 = a2;
a2 = result;
}
return result;
}
``````

1、n是从1开始的，而不是0
2、一般我们都会想到用递归的方式实现，但是这个时间开销很大：

``````int fibonacci(int n) {
if (n == 1)
return 0;
else if (n == 2)
return 1;
return fib(n-1) + fib(n-2);
}
``````

3、题目的引申: 青蛙跳阶梯，铺方砖