LeetCode - 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 toNULL.

Initially, all next pointers are set toNULL.

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

 

题意:

填充每个next指针,指向它的下一个右节点。如果没有下一个右节点,则应该将下一个指针设置为toNULL。

最初,所有next指针都设置为toNULL。

注意:

您可以只使用常量的额外空间。

您可以假设它是一个完美的二叉树(即,所有叶节点都位于同一级别,并且每个父节点都有两个子节点)。

 

解题思路:

树的层序遍历,既然是树的遍历那就可以使用递归来解决。

递归的思路:

首先判断左结点是否存在,存在就把左结点的next指针赋给 右结点。这里并不需要判断右结点是否存在,因为这是个完全二叉树,左结点存在那么右结点也一定存在了。

其次判断右结点是否存在,判断右结点存在之后有两种情况,

第一种是上面那种 5 的情况,这时候需要将右结点的next指针跨域赋给其父节点的兄弟结点的左结点。 

第二种是7的情况,那么需要将右结点赋null。

 

代码如下:

public void connect(TreeLinkNode root) {
	        if(root == null) {
	        	return;
	        }
	        
	        if(root.left != null) {
	        	root.left.next = root.right;
	        }
	        
	        if(root.right !=null) {
	        	if(root.next == null) {
	        		root.right.next = null;
	        	}
	        	else {
	        		root.right.next = root.next.left;
	        	}
	        }
	        
	        connect(root.left);
	        connect(root.right);
	 }

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值