Populating Next Right Pointers in Each Node

Given a binary tree java

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

Initially, all next pointers are set toNULL. spa

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, code

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

After calling your function, the tree should look like: it

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

分析:使用層次遍歷的方式,設置一個指針pre指向每層的第一個節點,另設一個指針指向當前節點。另外,最右側節點的next指針無需設定,其next指針默認爲null。 io

/**
 * 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;
        }
        TreeLinkNode pre = root;
        TreeLinkNode cur = null;
        
        while(pre.left != null){
            cur = pre;
            while(cur != null){
                cur.left.next = cur.right;
                if(cur.next != null){
                    cur.right.next = cur.next.left;
                }
                
                cur = cur.next;
            }
            
            pre = pre.left;
        }
    }
}
相關文章
相關標籤/搜索