LeetCode 第117题 填充每个节点的下一个右侧节点指针||

给定一个二叉树

struct Node {
  int val;
  Node *left;
  Node *right;
  Node *next;
}

填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL

初始状态下,所有 next 指针都被设置为 NULL

 

示例:

 

 

 

 1 class Solution117 {
 2 
 3   public Node connect(Node root) {
 4     if (root == null) {
 5       return null;
 6     }
 7 
 8     //node直接走到root的右兄弟处(根结点时,直接为null)
 9     Node node = root.next;
10 
11     //找到root的 右兄弟 中从左往右第一个不为空的孩子结点(如果没有,则找下一个右兄弟,直到没有右兄弟为止->null)
12     while (node != null) {
13       if (node.left != null) {
14         node = node.left;
15         break;
16       } else if (node.right != null) {
17         node = node.right;
18         break;
19       } else {
20         node = node.next;
21       }
22     }
23 
24     //如果左孩子不为空,就要替他找一个伴侣. 向右看第一个不为空的孩子.(右孩子 | 上一步中找到的左往右第一个不为空的孩子结点
25     if (root.left != null) {
26       root.left.next = (root.right == null ? node : root.right);
27     }
28 
29     //如果右孩子不为空,也要替他找一个伴侣. 即上一步中找到的左往右第一个不为空的孩子结点
30     if (root.right != null) {
31       root.right.next = node;
32     }
33 
34     //先扫描右孩子再扫描左孩子.
35     connect(root.right);
36     connect(root.left);
37 
38     return root;
39   }
40 
41 }

 

 

 

猜你喜欢

转载自www.cnblogs.com/rainbow-/p/10505623.html