From a4bb4a89aaf8fd53fd32e29373ff04d89ec98810 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=94=90=E6=A0=91=E6=A3=AE?= Date: Tue, 11 Jun 2019 23:58:58 +0800 Subject: [PATCH] Create 116. Populating Next Right Pointers in Each Node.md --- ...lating Next Right Pointers in Each Node.md | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 solutions/116. Populating Next Right Pointers in Each Node.md diff --git a/solutions/116. Populating Next Right Pointers in Each Node.md b/solutions/116. Populating Next Right Pointers in Each Node.md new file mode 100644 index 0000000..9d76deb --- /dev/null +++ b/solutions/116. Populating Next Right Pointers in Each Node.md @@ -0,0 +1,58 @@ +# [116. Populating Next Right Pointers in Each Node](https://leetcode.com/problems/populating-next-right-pointers-in-each-node/) +# 思路 +题目要求将满二叉树同一层的节点用指针串起来,要求空间复杂度O(1)。 + +## 思路一、递归 +最好想的还是递归: 如果root的左右子树都已经串好了的话,那么我们只需要将左子树每一层的最右边的节点的next指向右子树对应层最左边节点即可。 + +## 思路二、非递归 +由于next指针将每一层的节点都串起来了,所以我们可以很方便地从第一层的最左边节点开始访问第二层的所有节点、从第二层的最左边节点开始访问第三层的所有节点... +因此我们可以用这个思路从上往下依次将每一层串起来。我们用start表示每层的最左边节点,如果该层不是最后一层,那么我们应该将下一层所有节点串起来。 +该方法真正实现了空间复杂度O(1)。 + + + +# C++ +## 思路一 +``` C++ +class Solution { +public: + Node* connect(Node* root) { + if(root == NULL) return NULL; // 递归出口 + Node *p_left = connect(root -> left); // 左子树都已经串好了 + Node *p_right = connect(root -> right); // 右子树都已经串好了 + + // 将左子树每一层的最右边的节点的next指向右子树对应层最左边节点 + while(p_left){ + p_left -> next = p_right; + p_left = p_left -> right; + p_right = p_right -> left; + } + return root; + } +}; +``` + +## 思路二 +``` C++ +public: + Node* connect(Node* root) { + if(root == NULL) return NULL; + Node *start = root, *p = NULL; + while(start){ + p = start; + // p从每层开始节点起往右移动 + while(p){ + if(p -> left) { // 如果不是最后一层 + p -> left -> next = p -> right; + if(p -> next) // 如果不是本层的最后一个节点 + p -> right -> next = p -> next -> left; + } + p = p -> next; + } + start = start -> left; // 处理下一层 + } + return root; + } +}; +```