Jan 30 - Populating Next Right Pointers To Each Node; Iteration & Recursion; Tree; Pointer;
For example, we can do like this, in this way we may set up too many next pointer repeatedly.
Code:
/**
 * 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) {
        connect(root.left, root.right);
        
    }
    
    public void connect(TreeLinkNode left, TreeLinkNode right){
        if(left == null) return;
        
        left.next = right;
        connect(left.left, left.right);
        connect(left.right, right.left);
        connect(right.left, right.right);
    }
}
    However, we can do the set up next pointer efficiently using iterative way.
We use two pointer to do the set up operation. The head pointer points to the current node in a certain level. Pointer parent points to the parent of current ndoe. If head == null, we've reached to the bottom of the tree. Traversal completes. For a existed node, head.next = parent.right. And if parent.next exists, we should let parent.right.next = parent.next.left. Then go to parent.next.
Code:
public class Solution {
    public void connect(TreeLinkNode root) {
        if(root == null) return;
        for(TreeLinkNode head = root; head != null; head = head.left){
            for(TreeLinkNode parent = head; parent != null; parent = parent.next){
                TreeLinkNode child = parent.left;
                if(child == null) return;
                child.next = parent.right;
                if(parent.next != null) parent.right.next = parent.next.left;
                }
        }
    }
    /*
    public void connect(TreeLinkNode root) {
        if(root == null || root.left == null) return;
        connect(root.left, root.right);
    }
    
    public void connect(TreeLinkNode left, TreeLinkNode right){
        if(left == null) return;
        
        left.next = right;
        connect(left.left, left.right);
        connect(left.right, right.left);
        connect(right.left, right.right);
    }
    */
}
    이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.