题目:
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赋为null。 思路: 首先将每一层的最后一个结点的next赋值为null。 然后依次操作每一层,首先获取每一层的第一个结点。(其实二叉树和链表有点像,完美二叉树的最外两侧就可以看做两张链表,left和right指针类似链表的next指针) 引入两个指针,分别是cur和pre。 cur指向当前操作层,pre指向上一层。 1.cur是pre的左孩子,直接将cur的next指向pre的right结点,cur变成cur->next; 2.cur是pre的右孩子,并且pre的next不为null,cur->next指向pre->next->left; 3.cur是pre的右孩子,并且pre的next为null,说明cur已经指向了该层的最后一个结点,直接将cur->next赋为null即可。 执行到此处,要更新pre和cur,让它们分别指向自己下一层的第一个结点。(引入计数变量count,每次执行到此处count加1,根据count更新pre和cur) 循环结束条件:cur为null。 代码:
1 public void connect(TreeLinkNode root){ 2 if(root == null){ 3 return; 4 } 5 6 TreeLinkNode cur = root, pre = root; 7 //把每层最右侧的结点的next赋为null 8 while(cur != null){ 9 cur.next = null;10 cur = cur.right;11 }12 int count = 0;13 cur = root.left;14 while(true){15 if(cur == pre.left){16 cur.next = pre.right;17 cur = cur.next;18 }else{19 if(cur == pre.right && pre.next != null){20 cur.next = pre.next.left;21 cur = cur.next;22 pre = pre.next;23 }else{24 cur.next = null;25 count ++;26 pre = root;27 for(int i = 0; i < count; i++){28 pre = pre.left;29 }30 cur = pre.left;31 }32 }33 }34 35 }