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

解题方法

parent 替child 牽線: 相親樹

  1. BFS
  2. 紀錄每層的leader
    public void connect(TreeLinkNode root){
        //corner case
        if(root == null){
            return;
        }

        Queue<TreeLinkNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            for(int i = 0; i < size; i++){
                TreeLinkNode node = queue.poll();

                //next level
                if(node.left != null){
                    queue.offer(node.left);
                    node.left.next = node.right;
                }

                if(node.right != null){
                    queue.offer(node.right);
                    node.right.next = (i == size - 1) ? null : node.next.left;
                }
            }
        }
    }*/

    public void connect(TreeLinkNode root) {
        TreeLinkNode curr = root;
        while(curr != null){
            TreeLinkNode head = curr;
            while( curr != null){//當層跑完
                if(curr.left != null){
                    curr.left.next = curr.right;
                }
                if(curr.right != null){
                    curr.right.next = curr.next == null? null: curr.next.left;
                }
                curr = curr.next;
            }
            curr = head.left;
        }
    }

results matching ""

    No results matching ""