117. Populating Next Right Pointers in Each Node II

题目:

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

 

 

Hide Tags
  Tree Depth-first Search  

链接: http://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/

题解:

一样是DFS。跟上题不同在于,给定输入不是完全二叉树了,所以要加入一些条件来判断是否存在一个合理的next值。并且对左节点和右节点的有效性也要验证。最后要先递归连接右节点,再connect左节点。

Time Complexity - O(n), Space Complexity - O(1)。

public class Solution {

    public void connect(TreeLinkNode root) {

        if(root == null)

            return;

        TreeLinkNode node = root.next;

        while(node != null){

            if(node.left != null){

                node = node.left;

                break;

            } else if(node.right != null){

                node = node.right;

                break;

            } 

            node = node.next;

        }

        

        if(root.right != null){

            root.right.next = node;

            if(root.left != null)

                root.left.next = root.right;

        } else {

            if(root.left != null)

                root.left.next = node;

        }

        

        connect(root.right);

        connect(root.left);

    }

}

 

测试:

Reference:

http://www.cnblogs.com/springfor/p/3889327.html

你可能感兴趣的:(right)