[LeetCode]Populating Next Right Pointers in Each Node

题目:给定一颗完全二叉树,连接每个节点的next为该节点的右边同一层的节点

例如:

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
算法:

将根节点压入队列中
若队列不为空,则执行循环
	取出并弹出队列首节点
	if 队列不为空
	then
		if 当前节点和队列队首节点位于二叉树的同一层
		then current_node.next = next_node
		end
	end
	将当前节点的左孩子和右孩子压入队尾
/**
 * Definition for binary tree with next pointer.
 * public class TreeLinkNode {
 *     int val;
 *     TreeLinkNode left, right, next;
 *     TreeLinkNode(int x) { val = x; }
 * }
 */
public class Solution {
       /**
		 * Algorithm:
		 * 
		 * 1. push root into queue
		 * while queue is not empty
		 *     2. get and pop the top tree node from queue
		 *     3. if queue has any tree node more
		 *         4. if current_node and next_node at the same depth
		 *         5. then current_node.next = next_node
		 *     6. push current.node.left and current_node.right into queue
		 * 
		 */
	    public void connect(TreeLinkNode root) {
	    	if (null == root) {
	    		// Empty Tree
	    		return ;
	    	}
	    	
	        int counter = 0;  // means the ith node of the tree
	    	Queue<TreeLinkNode> queue = new LinkedList<TreeLinkNode>();
	        queue.add(root);
	        while (!queue.isEmpty()) {
	        	TreeLinkNode node = queue.poll();
	        	++counter;
	        	if (!queue.isEmpty()) {
	        		int curDepth = (int)(Math.log(1.0*counter)/Math.log(2.0));
	        		int nextDepth = (int)(Math.log(1.0*counter+1.0)/Math.log(2.0));
	        		if (curDepth == nextDepth) {
	        			TreeLinkNode nextNode = queue.peek();
	        			node.next = nextNode;
	        		}
	        	}
	        	
        		if (null != node.left) {
        			queue.add(node.left);
        		}
        		if (null != node.right) {
        			queue.add(node.right);
        		}
	        }
	    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值