Populating Next Right Pointers in Each Node

来源:互联网 发布:神户制钢造假 知乎 编辑:程序博客网 时间:2024/05/16 14:06

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 to NULL.

Initially, all next pointers are set to NULL.

Solution: Dynamic programming

public class Solution {    public void connect(TreeLinkNode root) {        if(root == null) return;        root.next = null;        subConnect(root);    }        public void subConnect(TreeLinkNode node){        if(node == null || node.left == null || node.right == null) return;        if(node.next == null){            node.left.next = node.right;            node.right.next = null;        }else{            node.left.next = node.right;            node.right.next = node.next.left;        }        subConnect(node.left);        subConnect(node.right);    }}


0 0
原创粉丝点击