码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_117_Populating Next Right Pointers in Each Node II

时间:2015-03-29 12:22:17      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

描述:

Follow up for problem "Populating Next Right Pointers in Each Node".

What if the given tree could be any binary tree? Would your previous solution still work?

Note:

  • You may only use constant extra space.

For example,
Given the following binary tree,

         1
       /        2    3
     / \        4   5    7

After calling your function, the tree should look like:

         1 -> NULL
       /        2 -> 3 -> NULL
     / \        4-> 5 -> 7 -> NULL

思路:

就是用两个list存储相邻两层的结点,把第i+1层结点存储到list中的同时,分别将第i层的各个节点指向下一个,跟116题Populating Next Right Pointers in Each Node I一个思路,就不重复写了。

代码:

/**
 * Definition for binary tree with next pointer.
 * public class TreeLinkNode {
 *     int val;
 *     TreeLinkNode left, right, next;
 *     TreeLinkNode(int x) { val = x; }
 * }
 */
public class Solution {
     public void connect(TreeLinkNode root)
	 {
	      if(root==null)
	    	  return ;
	      List<TreeLinkNode>list=new ArrayList<TreeLinkNode>();
	      List<TreeLinkNode>temp=new ArrayList<TreeLinkNode>();
	      TreeLinkNode node=null,tempNode=null;
	      list.add(root);
	      while(true)
	      {
	    	  tempNode=list.get(0);
	    	  if(tempNode.left!=null)
	    		  temp.add(tempNode.left);
	    	  if(tempNode.right!=null)
	    		  temp.add(tempNode.right);
	    	  for(int i=1;i<list.size();i++)
	    	  {
	    		  node=list.get(i);
	    		  if(node.left!=null)
		    		  temp.add(node.left);
		    	  if(node.right!=null)
		    		  temp.add(node.right);
		    	  tempNode.next=node;
		    	  tempNode=node;
	    	  }
	    	  if(temp.size()!=0)
	    	  {
	    		 list=temp;
	    		 temp=new ArrayList<TreeLinkNode>();
	    	  }
	    	  else
	    		  break;
	      }
	      return;
	 }
}

结果:

技术分享

leetcode_117_Populating Next Right Pointers in Each Node II

标签:

原文地址:http://blog.csdn.net/mnmlist/article/details/44725125

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!