这个题,我称作:找兄弟,next就是兄弟
要弄清楚家族里辈分关系
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.
- You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
For 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
理解题意以后,想清楚节点之间的关系,左节点和右节点是两种情况,左节点的next一定是他亲兄弟,右节点的next是他堂兄弟,由于二叉树只能向下遍历,所以要在父辈中传入左右孩子需要的next
public void connect(TreeLinkNode root) { help(root,null); } public void help(TreeLinkNode root,TreeLinkNode right) { if (root==null) return; root.next = right; help(root.left,root.right); if (right!=null) { help(root.right,right.left); } else help(root.right,null); }
第二部分:
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
这个题相对于上一问,改变的就是树可能不是perfect Tree,所以在找next的时候,左右节点都有可能是很远的“亲戚”,比如你叔叔没有孩子,那么你的next就是你二爷爷的孙子,甚至你二太爷爷的曾孙,等等...
所以在找next的时候要递归或者迭代实现,找到以后直接传递下去就行
我的悟性太差了,一开始发现这问题以后只是多判断了一下二爷爷的孙子,但是没有想到可能是更远的,后来错了才发现应该迭代。
这个问题也可以用迭代实现
public void connect(TreeLinkNode root) { help(root,null); } public void help(TreeLinkNode root,TreeLinkNode right) { if (root==null) return; root.next = right; TreeLinkNode next = finder(right); if (root.right!=null) { help(root.right,next); help(root.left,root.right); } else help(root.left,next); } public TreeLinkNode finder(TreeLinkNode node) { if (node!=null) { if (node.left!=null) return node.left; else if (node.right!=null) return node.right; else return finder(node.next); } else return null; }