给定一个满二叉树,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:
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":{"$id":"6","left":null,"next":null,"right":null,"val":6},"next":null,"right":{"$id":"7","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":{"$id":"6","left":null,"next":null,"right":null,"val":7},"right":null,"val":6},"right":null,"val":5},"right":null,"val":4},"next":{"$id":"7","left":{"$ref":"5"},"next":null,"right":{"$ref":"6"},"val":3},"right":{"$ref":"4"},"val":2},"next":null,"right":{"$ref":"7"},"val":1}
解释:给定二叉树如图 A 所示,你的函数应该填充它的每个next 指针,以指向其下一个右侧节点,如图 B 所示。
答案:
1public Node connect5(Node root) {
2 dfs(root, null);
3 return root;
4}
5
6private void dfs(Node curr, Node next) {
7 if (curr == null) return;
8 curr.next = next;
9 dfs(curr.left, curr.right);
10 dfs(curr.right, curr.next == null ? null : curr.next.left);
11}
解析:
看到这题我们首先想到的是递归。代码很好理解,再来看个类似的解法
1public Node connect3(Node root) {
2 if (root != null && root.left != null)
3 connectNodes(root.left, root.right);
4 return root;
5}
6
7public void connectNodes(Node node1, Node node2) {
8 node1.next = node2;
9 if (node1.left != null) {
10 connectNodes(node1.right, node2.left);
11 connectNodes(node1.left, node1.right);
12 connectNodes(node2.left, node2.right);
13 }
14}
注意题中说的是满二叉树,如果他的左子节点为空,那么他的右子节点也一定是为空的。下面再来看个非递归的解法
1public Node connect1(Node root) {
2 if (root == null)
3 return null;
4 Node pre = root;
5 Node cur = null;
6 while (pre.left != null) {
7 cur = pre;
8 while (cur != null) {
9 cur.left.next = cur.right;
10 if (cur.next != null)
11 cur.right.next = cur.next.left;
12 cur = cur.next;
13 }
14 pre = pre.left;
15 }
16 return root;
17}
这种解法也比较容易理解,他会一层一层的往下遍历,只有把当前层连完之后才会操作下一层