1. 程式人生 > 實用技巧 >填充每個節點的下一個右側節點指標

填充每個節點的下一個右側節點指標

填充每個節點的下一個右側節點指標

題目:給定一個完美二叉樹,其所有葉子節點都在同一層,每個父節點都有兩個子節點。二叉樹定義如下:

struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每個 next 指標,讓這個指標指向其下一個右側節點。如果找不到下一個右側節點,則將 next 指標設定為 NULL。

初始狀態下,所有 next 指標都被設定為 NULL。

輸入:{"$id":"1","left":{"$id":"2","left":{"$id":"3","left":null,"next":null,"right":null,"val":4},"next":null,"right":{"$id":"4","left":null,"next":null,"right":null,"val":5},"val":2},"next":null,"right":{"$id":"5","left":{"$id":"6","left":null,"next":null,"right":null,"val":6},"next":null,"right":{"$id":"7","left":null,"next":null,"right":null,"val":7},"val":3},"val":1}

輸出:{"$id":"1","left":{"$id":"2","left":{"$id":"3","left":null,"next":{"$id":"4","left":null,"next":{"$id":"5","left":null,"next":{"$id":"6","left":null,"next":null,"right":null,"val":7},"right":null,"val":6},"right":null,"val":5},"right":null,"val":4},"next":{"$id":"7","left":{"$ref":"5"},"next":null,"right":{"$ref":"6"},"val":3},"right":{"$ref":"4"},"val":2},"next":null,"right":{"$ref":"7"},"val":1}

解釋:給定二叉樹如圖 A 所示,你的函式應該填充它的每個 next 指標,以指向其下一個右側節點,如圖 B 所示。

解題思路:運用遞迴來解決,如果當前節點是父節點的左節點則將next設定為父節點的右節點,如果是右節點則將父節點的next節點的左節點設定為next即可

/*
// Definition for a Node.
class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;

    public Node() {}
    
    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, Node _left, Node _right, Node _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
};
*/

class Solution {
    public Node connect(Node root) {
        if(root == null)
            return null;
        dfs(root, null);
        return root;
    }
    
    /**
    需要藉助父節點的next來尋找next
    **/
    private void dfs(Node cur, Node parent) {
        if(cur == null)
            return ;
        
        //root
        if(parent == null) {
            cur.next = null;
            dfs(cur.left, cur);
            dfs(cur.right, cur);
            return ;
        }
            
        if(cur == parent.left) {
            cur.next = parent.right;
        } else {
            cur.next = parent.next == null ? null : parent.next.left;
        }
        
        dfs(cur.left, cur);
        dfs(cur.right, cur);
    }
}