力扣刷题——116. 填充每个节点的下一个右侧节点指针

116. 填充每个节点的下一个右侧节点指针

一开始的想法如下,但只通过部分样例

image-20230218210414552

class Solution {
		public Node connect(Node root) {

			if (root == null) {
				return null;
			}

			if (root.left != null) {
				root.left.next = root.right;
				if (root.left.right != null) {
					root.left.right.next = root.right.left;
				}
			}

			connect(root.left);
			connect(root.right);

			return root;
		}
	}

image-20230218214222222

因为一开始就想错了,当有第四层的时候就不适用了。。。

按别人思路改了一下,十分巧妙

class Solution {
		public Node connect(Node root) {

			if (root == null) {
				return null;
			}

			if (root.left != null) {
				root.left.next = root.right;
				if (root.next != null) {//如果root的next不为空,则可以让root的右节点连接next的左节点
					root.right.next = root.next.left;
				}
			}

			connect(root.left);
			connect(root.right);

			return root;
		}
	}

posted on 2023-02-18 21:57  pumpkinsBig  阅读(11)  评论(0)    收藏  举报

导航