Skip to main content

117, Populating Next Right Pointers in Each Node II

MikeAbout 7 minbinary treemediumbinary treelinked listdepth first searchbreadth first search

I Problem

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.

Example 1
picture117
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.

Example 2
Input: root = []
Output: []

Constraints

  • The number of nodes in the tree is in the range [0, 6000].
  • -100 <= Node.val <= 100

Follow up

  • You may only use constant extra space.
  • The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.

Related Topics

  • Linked List
  • Tree
  • Depth-First Search
  • Breadth-First Search
  • Binary Tree

II Solution

#[derive(Debug, PartialEq, Eq)]
pub struct Node {
    pub val: i32,
    pub left: Option<Rc<RefCell<Node>>>,
    pub right: Option<Rc<RefCell<Node>>>,
    pub next: Option<Rc<RefCell<Node>>>,
}

impl Node {
    pub fn new(val: i32) -> Option<Rc<RefCell<Node>>> {
        Some(Rc::new(RefCell::new(Node {
            val,
            left: None,
            right: None,
            next: None,
        })))
    }
    pub fn new_with_children(
        val: i32,
        left: Option<Rc<RefCell<Node>>>,
        right: Option<Rc<RefCell<Node>>>,
    ) -> Option<Rc<RefCell<Node>>> {
        Some(Rc::new(RefCell::new(Node {
            val,
            left,
            right,
            next: None,
        })))
    }
}
pub fn connect(root: Option<Rc<RefCell<Node>>>) -> Option<Rc<RefCell<Node>>> {
    //Self::bfs_iter_1(root)
    Self::bfs_iter_2(root)
}

fn bfs_iter_1(root: Option<Rc<RefCell<Node>>>) -> Option<Rc<RefCell<Node>>> {
    if let Some(root) = root.clone() {
        let mut queue = VecDeque::from([root]);

        while !queue.is_empty() {
            let level_len = queue.len();

            for i in 1..=level_len {
                if let Some(curr) = queue.pop_front() {
                    if i != level_len {
                        curr.borrow_mut().next = queue.front().cloned();
                    }

                    if let Some(left) = curr.borrow().left.clone() {
                        queue.push_back(left);
                    }
                    if let Some(right) = curr.borrow().right.clone() {
                        queue.push_back(right);
                    }
                }
            }
        }
    }

    root
}

fn bfs_iter_2(root: Option<Rc<RefCell<Node>>>) -> Option<Rc<RefCell<Node>>> {
    if let Some(root) = root.clone() {
        let mut queue = VecDeque::from([(root, 0)]);
        let mut prev: (Option<Rc<RefCell<Node>>>, i32) = (None, -1);

        while let Some((curr, level)) = queue.pop_front() {
            if prev.1 == level {
                prev.0.map(|prev| {
                    prev.borrow_mut().next = Some(curr.clone());
                });
            };
            prev = (Some(curr.clone()), level);

            if let Some(left) = curr.borrow().left.clone() {
                queue.push_back((left, level + 1));
            }
            if let Some(right) = curr.borrow().right.clone() {
                queue.push_back((right, level + 1));
            }
        }
    }

    root
}

Approach 2: Use Established Next Pointer

pub fn connect(root: Option<Rc<RefCell<Node>>>) -> Option<Rc<RefCell<Node>>> {
    //Self::use_next_pointer_iter(root)
    Self::use_next_pointer_recur(root)
}
///
/// Iteration
///
fn use_next_pointer_iter(root: Option<Rc<RefCell<Node>>>) -> Option<Rc<RefCell<Node>>> {
    let mut leftmost = root.clone();
    while let Some(left) = leftmost {
        let mut level = Some(left.clone());

        while let Some(curr) = level {
            // get child of curr node
            let child_of_curr =
                match (curr.borrow().left.clone(), curr.borrow().right.clone()) {
                    (Some(left), Some(right)) => {
                        // set RIGHT child node as the next pointer of LEFT child node
                        left.borrow_mut().next = Some(right.clone());
                        Some(right)
                    }
                    (Some(left), None) => Some(left),
                    (None, Some(right)) => Some(right),
                    (_, _) => None,
                };
            // set child node's next pointer
            if child_of_curr.is_some() && curr.borrow().next.is_some() {
                let mut next = curr.borrow().next.clone();

                while let Some(curr) = next {
                    if let Some(left) = curr.borrow().left.clone() {
                        child_of_curr.map(|child| {
                            child.borrow_mut().next = Some(left);
                        });
                        break;
                    }
                    if let Some(right) = curr.borrow().right.clone() {
                        child_of_curr.map(|child| {
                            child.borrow_mut().next = Some(right);
                        });
                        break;
                    }

                    next = curr.borrow().next.clone();
                }
            }

            level = curr.borrow().next.clone();
        }

        leftmost = if left.borrow().left.is_some() {
            left.borrow().left.clone()
        } else if left.borrow().right.is_some() {
            left.borrow().right.clone()
        } else {
            left.borrow().next.clone()
        };
    }

    root
}
///
/// Recursion(Pre-order Mirror)
///
fn use_next_pointer_recur(root: Option<Rc<RefCell<Node>>>) -> Option<Rc<RefCell<Node>>> {
     const PRE_ORDER: fn(Option<Rc<RefCell<Node>>>) = |root| {
         if let Some(curr) = root {
             // get child of curr node
             let child_of_curr =
                 match (curr.borrow().left.clone(), curr.borrow().right.clone()) {
                     (Some(left), Some(right)) => {
                         left.borrow_mut().next = Some(right.clone());
                         Some(right)
                     }
                     (Some(left), None) => Some(left),
                     (None, Some(right)) => Some(right),
                     (None, None) => None,
                 };
             // set child node's next pointer
             if let Some(child) = child_of_curr {
                 let mut next = curr.borrow().next.clone();
                 while let Some(curr) = next {
                     if let Some(left) = curr.borrow().left.clone() {
                         child.borrow_mut().next = Some(left);
                         break;
                     }
                     if let Some(right) = curr.borrow().right.clone() {
                         child.borrow_mut().next = Some(right);
                         break;
                     }
                     next = curr.borrow().next.clone();
                 }
             }

             // Here, the order must be right first and then left.
             PRE_ORDER(curr.borrow().right.clone());
             PRE_ORDER(curr.borrow().left.clone());
         }
     };

     PRE_ORDER(root.clone());

     root
}