Populating Next Right Pointers in Each Node

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).




给的两个先决条件大大减低了题目难度。 找规律:

1. 如果是左节点,那么它的next指向的是父节点的右节点。

2. 如果是右节点,那么它的next指向的是父节点的next的左节点。


/**
 * 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;
        }
        if(root.left!=null){
            root.left.next = root.right;
        }
        connect(root.left);
          
        if(root.right!=null){
            root.right.next = root.next==null?null:root.next.left;
        }
        connect(root.right);
    }
      
}

你可能感兴趣的:(java,LeetCode)