[Leetcode] 117. Populating Next Right Pointers in Each Node II

来源:互联网 发布:excel查询数据库 编辑:程序博客网 时间:2024/06/05 11:07

Follow up for problem "Populating Next Right Pointers in Each Node".

What if the given tree could be any binary tree? Would your previous solution still work?

Note:

  • You may only use constant extra space.

For example,
Given the following binary tree,

         1       /  \      2    3     / \    \    4   5    7

After calling your function, the tree should look like:

         1 -> NULL       /  \      2 -> 3 -> NULL     / \    \    4-> 5 -> 7 -> NULL

/** * 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) {        if(root == null) return;        TreeLinkNode parent = root;        while(parent != null){            TreeLinkNode next = null;            TreeLinkNode current = null;            while(parent != null){                if(next == null){                    if(parent.left == null){                        next = parent.right;                    } else {                        next = parent.left;                    }                }                if(parent.left != null){                    if(current == null){                        current = parent.left;                    } else {                        current.next = parent.left;                        current = current.next;                    }                }                if(parent.right != null){                    if(current == null){                        current = parent.right;                    } else {                        current.next = parent.right;                        current = current.next;                    }                }                parent = parent.next;            }            parent = next;        }    }}


0 0