264,填充每个节点的下一个右侧节点指针 II
作者:互联网
给定一个二叉树
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
输入:
{"$id":"1","left":{"$id":"2","left":{"$id":"3","left":null,"next":null,"right":null,"val":4},"next":null,"right":{"$id":"4","left":null,"next":null,"right":null,"val":5},"val":2},"next":null,"right":{"$id":"5","left":null,"next":null,"right":{"$id":"6","left":null,"next":null,"right":null,"val":7},"val":3},"val":1}
输出:
{"$id":"1","left":{"$id":"2","left":{"$id":"3","left":null,"next":{"$id":"4","left":null,"next":{"$id":"5","left":null,"next":null,"right":null,"val":7},"right":null,"val":5},"right":null,"val":4},"next":{"$id":"6","left":null,"next":null,"right":{"$ref":"5"},"val":3},"right":{"$ref":"4"},"val":2},"next":null,"right":{"$ref":"6"},"val":1}
解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。
答案:
1public Node connect1(Node root) {
2 if (root == null) return root;
3 Node curP = root;
4 Node nextDummyHead = new Node(0);
5 Node p = nextDummyHead;
6 while (curP != null) {
7 if (curP.left != null) {
8 p.next = curP.left;
9 p = p.next;
10 }
11 if (curP.right != null) {
12 p.next = curP.right;
13 p = p.next;
14 }
15 if (curP.next != null) {
16 curP = curP.next;
17 } else {
18 curP = nextDummyHead.next;
19 nextDummyHead.next = null;
20 p = nextDummyHead;
21 }
22 }
23 return root;
24}
解析:
这题和上一题不一样的是,这题他不是满二叉树,所以难度比上一题也更难一些。这个也是一层一层的连接,他在遍历当前层的时候,会把下一层的节点用p全部串起来,这里的p,curp和nextDummyHead我们可以把它当做一个链表。第15行有个判断,如果条件成立,说明当前节点还没遍历完,就还遍历当前节点。如果条件不成立,就会执行18到20行的代码进入下一层。如果还是理解不了,我们可以稍微再改一下
1public Node connect(Node root) {
2 Node temp = root;
3 while (temp != null) {
4 Node tempChild = new Node(0);
5 Node currentChild = tempChild;
6 while (temp != null) {
7 if (temp.left != null) {
8 currentChild.next = temp.left;
9 currentChild = currentChild.next;
10 }
11 if (temp.right != null) {
12 currentChild.next = temp.right;
13 currentChild = currentChild.next;
14 }
15 temp = temp.next;
16 }
17 temp = tempChild.next;
18 }
19 return root;
20}
第一个while循环是从上一层一层的往下走,第二个while循环是在当前层从左往右走。原理都是一样的,当这种解法比第一种更容易理解一些。
标签:Node,right,val,next,II,264,null,节点,left 来源: https://blog.51cto.com/u_4774266/2902471