Solution 1
这里面要求在既有链表结构上完成先序遍历的结构调整,也就是在调整过程中不改变树在先序遍历上的逻辑顺序,其实和 0094. Binary Tree Inorder Traversal 中的Morris遍历法在中序遍历上的思路一致,只需要修改遍历方法,以及最后的指针操作调整即可。
- 因为对右侧遍历不做任何操作,因此当当前节点左子树为空时,不做任何操作
- 找到当前节点右子树的理想前驱节点后,将右子树接到其右侧,然后将当前节点左子树切换到右子树(要求全是右子树),并将左子树置空
- 时间复杂度: O ( n ) O(n) O(n),其中 n n n为输入树的节点个数,完成调整需要完成一次遍历
- 空间复杂度: O ( 1 ) O(1) O(1),仅维护常数个状态量,Morris法一个最大的优势就是可以不占用额外空间
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void flatten(TreeNode* root) {
auto now = root;
while (now != nullptr) {
if (now->left != nullptr) {
auto pre = now->left;
while (pre->right != nullptr) { pre = pre->right; }
pre->right = now->right;
now->right = now->left;
now->left = nullptr;
}
now = now->right;
}
}
};
Solution 2
Solution 1的Python实现
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def flatten(self, root: Optional[TreeNode]) -> None:
"""
Do not return anything, modify root in-place instead.
"""
now = root
while now is not None:
if now.left is not None:
pre = now.left
while pre.right is not None: pre = pre.right
pre.right = now.right
now.right = now.left
now.left = None
now = now.right