56.删除链表中重复的节点
public class Solution {
public ListNode deleteDuplication(ListNode pHead)
{
ListNode first = new ListNode(-1);
first.next = pHead;
ListNode newHead = first;
while(pHead!=null&&pHead.next!=null){
if(pHead.val ==pHead.next.val){
int value = pHead.val;
while(pHead!=null&&pHead.val==value){
pHead=pHead.next;
}
first.next = pHead;
}else{
first = pHead;
pHead = pHead.next;
}
}
return newHead.next;
}
}
57.二叉树的下一个节点
public class Solution {
public TreeLinkNode GetNext(TreeLinkNode pNode)
{
if(pNode==null){
return null;
}
if(pNode.right!=null){
pNode = pNode.right;
while(pNode.left!=null){
pNode = pNode.left;
}
return pNode;
}
while(pNode.next!=null){
if(pNode.next.left==pNode){
return pNode.next;
}
pNode = pNode.next;
}
return null;
}
}
58.对称的二叉树
public class Solution {
boolean isSymmetrical(TreeNode pRoot)
{
if(pRoot==null){
return true;
}
return duichen(pRoot.left,pRoot.right);
}
public boolean duichen(TreeNode left,TreeNode right){
if(left==null){
return right==null;
}else if(right==null){
return false;
}
if(left.val!=right.val){
return false;
}
return duichen(left.left,right.right)&&duichen(left.right,right.left);
}
}
59.按之字形打印树
import java.util.ArrayList;
import java.util.*;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> res = new ArrayList();
if(pRoot==null){
return res;
}
Stack<TreeNode> st1 =new Stack();
Stack<TreeNode> st2 = new Stack();
st1.push(pRoot);
int floor = 1;
while(!st1.empty()||!st2.empty()){
if(floor%2!=0){
ArrayList<Integer> temp = new ArrayList();
while(!st1.isEmpty()){
TreeNode tempnode = st1.pop();
if(tempnode!=null){
temp.add(tempnode.val);
st2.push(tempnode.left);
st2.push(tempnode.right);
}
}
if(!temp.isEmpty()){
res.add(temp);
floor++;
}
}else{
ArrayList<Integer> temp = new ArrayList();
while(!st2.isEmpty()){
TreeNode tempnode = st2.pop();
if(tempnode!=null){
temp.add(tempnode.val);
st1.push(tempnode.right);
st1.push(tempnode.left);
}
}
if(!temp.isEmpty()){
res.add(temp);
floor++;
}
}
}
return res;
}
}
60.二叉树打印成多行(树的层序遍历)
import java.util.ArrayList;
import java.util.*;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
Queue<TreeNode> qu = new LinkedList();
ArrayList<ArrayList<Integer>> res = new ArrayList();
if(pRoot==null){
return res;
}
qu.add(pRoot);
while(!qu.isEmpty()){
int count = qu.size();
ArrayList<Integer> list = new ArrayList();
while(count>0){
TreeNode temp = qu.remove();
list.add(temp.val);
if(temp.left!=null){
qu.add(temp.left);
}
if(temp.right!=null){
qu.add(temp.right);
}
count--;
}
res.add(list);
}
return res;
}
}