111.Populating Next Right Pointers in Each Node

Given a binary tree

    struct TreeLinkNode {
      TreeLinkNode *left;
      TreeLinkNode *right;
      TreeLinkNode *next;
    }

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

Initially, all next pointers are set to NULL.

Note:

  • You may only use constant extra space.
  • You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).

For example,
Given the following perfect binary tree,

         1
       /  \
      2    3
     / \  / \
    4  5  6  7

After calling your function, the tree should look like:

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

Subscribe to see which companies asked this question。

分析:给定一个完全二叉树,给每个结点加上其可以指向所在层的右边结点,没有的话则指向null。

首先按层找到每一层的结点,然后让每个结点指向其右边的结点。

	/**
	 * 给定一个完全二叉树,给每个结点加上其可以指向所在层的右边结点,没有的话则指向null。
	 * Step1:按层获取每层的结点;
	 * Step2:每层的结点right指向其右边结点,最右边指向null。
	 * @date 20160417 
	 */
	 public void connect(TreeLinkNode root) {
	     /*如果根结点为空则直接返回*/   
		 if(root == null){
	        	return;
	        }
		 List<TreeLinkNode> currentlist = new ArrayList<TreeLinkNode>();//存放当前层的结点,初始化时放入根结点
		 List<TreeLinkNode> nextlist = new ArrayList<TreeLinkNode>();//当前层的孩子结点层
		 currentlist.add(root);
		 TreeLinkNode node ;
	     while(currentlist.size()!=0){
	    	 int size = currentlist.size();
	    	 /*依次遍历当前层中每个结点,并把拿到的结点的next指向其下一个结点,同时把当前结点的孩子结点放到孩子层*/
	    	 int i=0;
	    	 for(;i<size-1;i++){
	    		 node = currentlist.get(i);
	    		 node.next = currentlist.get(i+1);
	    		 if(node.left!=null){
	    			 nextlist.add(node.left);
	    		 }
	    		 if(node.right!=null){
	    			 nextlist.add(node.right);
	    		 }
	    	 }
	    	 node=currentlist.get(i);
	    	 node.next =null;//当前层的最右边指向null
	    	 if(node.left!=null){
    			 nextlist.add(node.left);
    		 }
    		 if(node.right!=null){
    			 nextlist.add(node.right);
    		 }
    		 
    		 currentlist.clear();
    		 currentlist.addAll(nextlist);
    		 nextlist.clear();
    		 
	     }//end while   
	 }


你可能感兴趣的:(111.Populating Next Right Pointers in Each Node)