Leetcode: Populating Next Right Pointers in Each Node II

来源:互联网 发布:网络入侵 编辑:程序博客网 时间:2024/05/12 17:16

Problem:

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


My Solution:

Main idea: Still pre-order traverse, but note that this time it must traverse the right child first, since we need to traverse all the nodes on the right to the parent in the parent's level in some cases.

1. For the left child, if the right child exist, assign its next pointer to the right child. Otherwise, traverse the nodes on the right side to the parent on the parent's level, break the loop until one node's left child exists or its right child exists.

2. For the right child, traverse the nodes on the right side to the parent on the parent's level, break the loop until one node's left child exists or its right child exists. 

3. Do the recursion, note that the recursion must start from the right child.


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


0 0
原创粉丝点击