Given a binary tree
struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; }
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL
.
Initially, all next pointers are set to NULL
.
Note:
- You may only use constant extra space.
- Recursive approach is fine, implicit stack space does not count as extra space for this problem.
- You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
Example:
Given the following perfect binary tree,
1 / \ 2 3 / \ / \ 4 5 6 7
After calling your function, the tree should look like:
1 -> NULL / \ 2 -> 3 -> NULL / \ / \ 4->5->6->7 -> NULL
思路:题目明确要求不许用额外空间,递归栈除外。所以这一道标准的二叉树遍历。
处理完左右节点后,要将左右子树链接起来,而不仅仅是左右节点,这点切记!!如果只连接左右节点的话,当处理层数为4的完全二叉树时,会第4层的前4个节点与后4个节点是分离的!!
写法1:
/** * 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 TreeLinkNode dfs(TreeLinkNode node){ if(node == null) return null; if(node.left == null && node.right == null) return node; TreeLinkNode lnode = dfs(node.left); TreeLinkNode rnode = dfs(node.right); lnode.next = rnode; if(lnode.right != null && rnode.left != null){ TreeLinkNode lrSonNode= lnode.right; TreeLinkNode rlSonNode= rnode.left; while(lrSonNode != null &&rlSonNode != null){ lrSonNode.next = rlSonNode; lrSonNode = lrSonNode.right; rlSonNode = rlSonNode.left; } } return node; } public void connect(TreeLinkNode root) { dfs(root); } }
写法2:
/** * 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; if( root.left != null ) { root.left.next = root.right; } if( root.right != null) { if( root.next != null ) { root.right.next = root.next.left; } } connect( root.left ); connect( root.right ); } }