非递归的方法:
若 root 左子树非空,则找到左子树的最右节点,将右子树接到右节点 再将左子树移到根节点的右节点上,root 不断更新成右节点,最后得到输出
class Solution {
public:
void flatten(TreeNode* root) {
TreeNode* last = nullptr;
while(root){
if(root->left) {
last = root->left;
while(last->right) last = last->right;
last->right = root->right;
root->right = root->left;
root->left = nullptr;
}
root = root->right;
}
}
};
递归 + 前序遍历 dfs:
class Solution {
TreeNode* dfs(TreeNode* tree) {
if(!tree) return nullptr;
TreeNode* l_tree = tree->left;
TreeNode* r_tree = tree->right;
tree->left = nullptr;
tree->right = dfs(l_tree);
TreeNode* current = tree;
while(current->right) current = current->right;
current->right = dfs(r_tree);
return tree;
}
public:
void flatten(TreeNode* root) {
dfs(root);
}
};
|