题目1:
从上往下打印二叉树:从上往下打印出二叉树的每个节点,同层节点从左至右打印。
比较简单,用队里来实现,直接贴程序:
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> array=new ArrayList<Integer>();
Deque<TreeNode> deque = new LinkedList<TreeNode>();
if(root!=null){
deque.offer(root);
}
while(!deque.isEmpty()){
TreeNode tree = deque.pop();
array.add(tree.val);
if(tree.left!=null){
deque.offer(tree.left);
}
if(tree.right!=null){
deque.offer(tree.right);
}
}
return array;
}
题目2:二叉搜索树的后序遍历序列:
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
思路:注意到这个是而二叉搜索树,那么就有个重要的特点,他的排序是 小 中 大,后序排列的顺序是,左 右 根,那么我们就能根数组,把最后一项找出来,最后一项就是他的根,遍历这个数组,判断是否前面一段数都是小于根,后面一段都是大于根,如果不是,立马返回不是,是的话就递归查找他的左右子树;
Copy:
public boolean VerifySquenceOfBST(int [] sequence) {
if(sequence.length==0)
return false;
return helper(0,sequence.length-1,sequence);
}
public boolean helper(int left,int right,int [] sequence){
if(left>=right)
return true;
int root=sequence[right];
int index=right;
for(int i=left;i<right;i++){
if(sequence[i]>root){
index=i;
break;
}
}
for(int i=index;i<right;i++){
if(sequence[i]<root){
return false;
}
}
return helper(left,index-1,sequence)&&helper(index,right-1,sequence);
}
题目3:二叉树中和为某一值的路径
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
思路:就是DFS。。。。
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
ArrayList<ArrayList<Integer>> listAll=new ArrayList<ArrayList<Integer>>();
LinkedList<Integer> list =new LinkedList<>();
DFS(root,target,list,listAll);
return listAll;
}
public void DFS(TreeNode node,int target,LinkedList<Integer> list,ArrayList<ArrayList<Integer>> listAll){
if(node==null){
return ;
}
target-=node.val;
if(node.left==null&&node.right==null){
if(target==0){
list.add(node.val);
listAll.add(new ArrayList(list));
list.removeLast();
}
return ;
}
list.add(node.val);
DFS(node.left,target,list,listAll);
DFS(node.right,target,list,listAll);
list.removeLast();
}
题目4:复杂链表的复制
题目描述:
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
思路:用一个Hash表来存储这个关系,键为原链表,值为新链表,那么新链表的连接顺序在遍历老链表的时候就可以创建出来了,而每个节点的随机节点可以通过老节点指向的老节点记做B,通过B来作为键找对对应的新节点。
public RandomListNode Clone(RandomListNode pHead){
HashMap<RandomListNode,RandomListNode> map=new HashMap<>();
RandomListNode head=new RandomListNode(0);
RandomListNode cur=head;
while(pHead!=null){
cur.next=new RandomListNode(pHead.label);
map.put(pHead,cur.next);
pHead=pHead.next;
cur=cur.next;
}
for(Map.Entry<RandomListNode,RandomListNode> m:map.entrySet() ){
m.getValue().random=map.get(m.getKey().random);
}
return head.next;
}
题目5:二叉搜索树与双向链表
题目描述:
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
思路:注意到这是一个二叉搜索树,小 中 大,直接中序遍历这个二叉树,改变指针的指向即可;