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; } * } */ /** * 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 p1 = root; TreeLinkNode p2 = null; TreeLinkNode p3 = null; while(p1!=null) { while(p1!=null) { if(p1.left!=null) { if(p2==null) { p2 = p1.left; p3 = p1.left; } else { p2.next = p1.left; p2 = p1.left; } } if(p1.right!=null) { if(p2==null) { p2 = p1.right; p3 = p1.right; } else { p2.next = p1.right; p2 = p1.right; } } p1 = p1.next; } p1 = p3; p2 = null; p3 = 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) { TreeLinkNode lastLevelHead = root; while (lastLevelHead != null) { TreeLinkNode p = lastLevelHead; TreeLinkNode newLevelHead = null; TreeLinkNode next = null; TreeLinkNode cur = null; boolean isLeft = true; while (p != null) { if (isLeft) { next = p.left; isLeft = false; } else { next = p.right; isLeft = true; } if (next != null) { if (newLevelHead == null) { newLevelHead = next; } if (cur == null) { cur = next; } else { cur.next = next; cur = next; } next = null; } if (isLeft) { p = p.next; } } lastLevelHead = newLevelHead; } } }
没有评论:
发表评论