Personal Blog
  • 💻Notes for Computer Science
  • Leetcode
    • Array
      • Container with most water
      • 3Sum
      • Next Permutation
      • Valid Sudoku
      • Permutation II
      • Combination Sum
      • Triangle
      • Maximal Square
      • Pairs of Songs with Total Duration Divisible by 60
      • Numbers At Most N Given Digit Set
      • Possible Sum
      • Swap Lex Order
      • Partition Equal Subset Sum
      • Domino and Tromino
      • Numbers At Most N Given Digits
      • Car Pooling
      • Surrounding Regions
      • Min Size Subarray Sum
      • Burst Balloons
      • Jump Game I
      • Jump Game II
      • House Robber II
      • Delete and Earn
      • Word Break
      • Decode Ways
      • Longest Increasing Subsequence
      • Cherry Pickup
      • Rotate Image
    • LinkedList
      • IsListPalindrome
      • Linked List Cycle
      • MergeTwoLinkedList
      • ReverseNodeInKGroup
      • RearrangeLastN
      • Remove Duplicates From Sorted List
      • RemoveKFromList
    • String
      • Generate Parentheses
      • Longest Valid Parentheses
      • Longest Common Subsequence
      • Count and Say
      • Decode String
      • Permutation in String
    • Tree
      • House Robber III
      • Convert Sorted Array to Binary Search Tree
      • Restore Binary Tree
      • Populating Next Right Pointers in Each Node II
      • Subtree of Another Tree
    • Graph
      • All Paths from Source to Target
      • Reorder Routes to Make All Paths Lead to the City Zero
      • Max Points on a Line
  • DBMS
    • DBMS Notes
  • Web App
    • Web Design
    • JavaScript
    • React.js
    • ReactNative
    • Mobile Design
    • Dialogue Flow
  • AnaplanIntern
    • Splunk
    • Docker
    • Kubernetes
  • 💰 Notes for Finance Concept
  • Analysis Concept
    • Volume Spread Analysis
    • Smart Money Concepts
Powered by GitBook
On this page
  • Idea
  • Code
  1. Leetcode
  2. Tree

Populating Next Right Pointers in Each Node II

ID: 117

PreviousRestore Binary TreeNextSubtree of Another Tree

Last updated 3 years ago

Given a binary tree

struct Node {
  int val;
  Node *left;
  Node *right;
  Node *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 to NULL.

Initially, all next pointers are set to NULL.

Input: root = [1,2,3,4,5,null,7]
Output: [1,#,2,3,#,4,5,7,#]
Explanation: Given the above binary tree (Figure A), 
your function should populate each next pointer to point to its 
next right node, just like in Figure B. The serialized output is in 
level order as connected by the next pointers,
with '#' signifying the end of each level.

Idea

BFS

BFS on each level of the tree, keep track of previous node and if the previous node is not the last one of the level, set the current node as the next element of the previous node

Not best time efficient, but enhance on BFS

Code

public Node connect(Node root) {
    if(root==null){
        return null;
    }        
    Queue<Node> q = new LinkedList<>();
    q.offer(root);
    while(!q.isEmpty()){
       int size = q.size();
        Node prev = q.poll();
        size--;
        while(size-- >0){
            Node curr = q.poll();
            prev.next = curr;
            if(prev.left!=null){
                q.offer(prev.left);
            }
            if(prev.right!=null){
                q.offer(prev.right);
            }
            prev = curr;        
    }
        if(prev.left!=null){
            q.offer(prev.left);
        }
        if(prev.right!=null){
            q.offer(prev.right);
        }
    }
    return root;
}