Given a binary tree java
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 toNULL. node
Initially, all next pointers are set toNULL. spa
Note: 指针
For example,
Given the following perfect binary tree, code
1 / \ 2 3 / \ / \ 4 5 6 7
After calling your function, the tree should look like: it
1 -> NULL / \ 2 -> 3 -> NULL / \ / \ 4->5->6->7 -> NULL
分析:使用层次遍历的方式,设置一个指针pre指向每层的第一个节点,另设一个指针指向当前节点。另外,最右侧节点的next指针无需设定,其next指针默认为null。 io
/** * 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 pre = root; TreeLinkNode cur = null; while(pre.left != null){ cur = pre; while(cur != null){ cur.left.next = cur.right; if(cur.next != null){ cur.right.next = cur.next.left; } cur = cur.next; } pre = pre.left; } } }