首页 > 代码库 > [Leetcode] Populating Next Right Pointers in Each Node II

[Leetcode] 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

 

Solution:

http://blog.csdn.net/wzy_1988/article/details/17412025

这道题目首要是找到右孩子的第一个有效的next链接节点,然后再处理左孩子。然后依次递归处理右孩子,左孩子

 1 /** 2  * Definition for binary tree with next pointer. 3  * public class TreeLinkNode { 4  *     int val; 5  *     TreeLinkNode left, right, next; 6  *     TreeLinkNode(int x) { val = x; } 7  * } 8  */ 9 public class Solution {10     public void connect(TreeLinkNode root) {11         if (root == null)12             return;13         TreeLinkNode p = root.next;14         while (p != null) {15             if(p.left!=null){16                 p=p.left;17                 break;18             }19             if(p.right!=null){20                 p=p=p.right;21                 break;22             }23             p=p.next;24         }25         if (root.right != null) {26             root.right.next = p;27         }28         if (root.left != null) {29             root.left.next = (root.right == null) ? p : root.right;30         }31         connect(root.right);32         connect(root.left);33     }34 }

 

[Leetcode] Populating Next Right Pointers in Each Node II