题目包括:
1. 输入一棵二叉树,求该树的深度。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
int TreeDepth(TreeNode* root)
{
if(!root)
return 0;
else
return TreeDepth(root->left)>TreeDepth(root->right)?TreeDepth(root->left)+1:TreeDepth(root->right)+1;
}
};
2. 判断有序二维数组是否存在target
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
int row = array.size(); //有几行
int col = array[0].size(); //有几列
int i=row-1,j=0;
while(i>0 && j<col-1){
if(array[i][j]<target)
j++;
if(array[i][j]>target)
i--;
if(target == array[i][j])
return true;
}
return false;
}
};
3. 将一个字符串中的每个空格替换成“%20”。
class Solution {
public:
void replaceSpace(char *str,int length) {
int countSpace = 0;
for(int i=0; i<length; i++){
if(str[i] == ' ')
countSpace++;
}
for(int i=length-1; i>=0; i--){
if(str[i] != ' ')
str[i+countSpace*2] = str[i];
else{
countSpace--;
str[i+countSpace*2] = '%';
str[i+countSpace*2+1] = '2';
str[i+countSpace*2+2] = '0';
}
}
}
};
4. 输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
/**
* public class ListNode {
* int val;
* ListNode next = null;
*
* ListNode(int val) {
* this.val = val;
* }
* }
*
*/
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode ln) {
Stack<Integer> stack = new Stack<Integer>();
ArrayList<Integer> al = new ArrayList<Integer>();
while(ln != null){
stack.push(ln.val);
ln = ln.next;
}
while(!stack.isEmpty())
al.add(stack.pop());
return al;
}
}
5. 通过前序和中序建二叉树
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回
/**
* 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) {
TreeNode root = reConstructBinaryTree(pre, in, 0, 0,pre.length-1, in.length-1);
return root;
}
public TreeNode reConstructBinaryTree(int [] pre, int [] in, int h1, int h2, int l1, int l2){
if(h1>l1||h2>l2)
return null;
int i = searchIndex(pre[h1], in, h2);
TreeNode root = new TreeNode(pre[h1]);
root.left = reConstructBinaryTree(pre, in, h1+1, h2, h1+i-h2, i-1);
root.right = reConstructBinaryTree(pre, in, h1+i-h2+1, i+1,l1, l2);
return root;
}
public int searchIndex(int target, int [] in, int h2){
int i = h2;
while(target != in[i]) i++;
return i;
}
}