LeetCode 链表2_27+二叉树的遍历(递归与非递归)

---恢复内容开始---

19. 删除链表的倒数第N个节点

实现原理:设置两个指针p,q,初始时先让p走n步,之后p与q一起走,当p走到结尾的时候,删除p.next即可。

public ListNode removeNthFromEnd2(ListNode head, int n) {
		
		  ListNode dummy=new ListNode(-1);
		  dummy.next=head;
		  ListNode p=dummy;
		  ListNode q=dummy;
		  
//		  先让qp先走n步
		  for(int i=0;i<n;i++){
			  p=p.next;
		  }
//		  之后一起走
		  while(p.next!=null){
			  p=p.next;
			  q=q.next;
		  }
		  q.next=q.next.next;
		  
		   return dummy.next;
	}

 

 二叉树遍历:

递归方式遍历:

public void Order(TreeNode root){
		if(root==null) return ;
		
//		先序
		System.out.println(root.val);
		Order(root.left);
		Order(root.right);
		
//		中序
		Order(root.left);
		System.out.println(root.val);
		Order(root.right);
		
//		后序
		Order(root.left);
		Order(root.right);
		System.out.println(root.val);
		
	}

非递归版本:

先序遍历:

//	先序遍历
//	实现原理:创建一个栈空间,每次进行访问的时候都是同样的压入进栈,直到节点的左孩子为空的时候,将其出栈,方向转到其右孩子上面

	 public List<Integer> preorderTraversal(TreeNode root) {
		if(root==null) return null;
		List<Integer> result=new  ArrayList<Integer>();
		Stack<TreeNode> s=new Stack<>();
		
		while(!s.isEmpty() || root!=null){
			while(root!=null){
				result.add(root.val);
				s.push(root);
				root=root.left;
			}
			
			if(!s.isEmpty()){
			root=s.pop();
			root=root.right;
			}
		}
		 return result;
		 
		
	 }

中序遍历:

//	 中序遍历
	 public List<Integer> inorderTraversal(TreeNode root) {
//		 实现策略跟先序类似,只是压入进栈的时间问题
		 
		 List<Integer> result=new ArrayList<>();
		 Stack<TreeNode> s=new Stack<>();
		 
		 while(!s.isEmpty()||root!=null){
			while(root!=null){
				s.push(root);
				root=root.left;
			}
			
			if(!s.isEmpty()){
				root=s.pop();
				result.add(root.val);
				root=root.right;		
			}	
		 } 
		 return result; 
	 }

 后序遍历:

实现原理:
* 需要保证根节点在左孩子和右孩子都被访问之后才能访问,有几个临界条件:
* 对于任意的一个节点P,先将其入栈,如果p不存在左右孩子,则可以直接访问;
* 或者其存在左孩子或者右孩子,但是其左孩子和右孩子都已经被访问过了,则同样可以进行直接访问该节点。
* 若非上述情况,则需要将其右左孩子依次入栈,这样就保证了在访问的时候,左孩子在右孩子的前面,
* 左孩子和右孩子都在根节点的前面被访问。

public List<Integer> postorderTraversal2(TreeNode root){
		 
		 List<Integer> result=new ArrayList<>();
		 Stack<TreeNode> s=new Stack<>();
		 //注意返回的数据类型
		 if(root==null){
			 return result;
		 }
		 
		 TreeNode cur;
		 TreeNode prev=null;
		 
		 s.push(root);
		 while(!s.isEmpty()){
			cur=s.peek();
			if((cur.left==null && cur.right==null) || 
			(prev!=null &&(prev==cur.left ||prev==cur.right ))){
				result.add(cur.val);
				s.pop();
				prev=cur;
			}
			else{
				if(cur.right!=null){
					s.push(cur.right);
				}
				if(cur.left!=null){
					s.push(cur.left);
				}
			} 
		 }
		 return result;
	 }
	 

  

猜你喜欢

转载自www.cnblogs.com/qian2015/p/10445529.html