Populating Next Right Pointers in Each Node leetcode java
题目:
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是null,
说明当前节点已经到了最右边,那么右孩子也是最右边的,所以右孩子指向null。如果当前节点的next不是null,那么当前节点的右孩子的next就需要
指向当前节点next的左孩子。
递归求解就好。
代码如下:
1 public void connect(TreeLinkNode root) {
2 if(root==null)
3 return;
4 if(root.left!=null)
5 root.left.next=root.right;
6 if(root.right!=null){
7 if(root.next!=null)
8 root.right.next = root.next.left;
9 else
10 root.right.next = null;
11 }
12 connect(root.left);
13 connect(root.right);
14 }
2 if(root==null)
3 return;
4 if(root.left!=null)
5 root.left.next=root.right;
6 if(root.right!=null){
7 if(root.next!=null)
8 root.right.next = root.next.left;
9 else
10 root.right.next = null;
11 }
12 connect(root.left);
13 connect(root.right);
14 }