您的位置:首页 > Web前端 > Node.js

Populating Next Right Pointers in Each Node

2013-08-19 01:01 357 查看
//recursive, log(n) space cpmplexity
public void connect(TreeLinkNode root) {
// Start typing your Java solution below
// DO NOT write main() function
if(root == null) return;
if(root.left != null) root.left.next = root.right;
if(root.right != null) root.right.next = (root.next == null) ? null : root.next.left;
connect(root.left);
connect(root.right);
}

//iterative, constant space cpmplexity
    public void connect(TreeLinkNode root) {
        // Start typing your Java solution below
        // DO NOT write main() function
        while(root != null) {
            TreeLinkNode tmp = root;
            while(tmp != null) {
                if(tmp.left != null) tmp.left.next = tmp.right;
                if(tmp.right != null && tmp.next != null) tmp.right.next = tmp.next.left;
                tmp = tmp.next;
            }
            root = root.left;
        }
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: