classSolution{public:voidflatten(TreeNode*root){if(root==nullptr)return;flatten(root->left);flatten(root->right);TreeNode*constleft=root->left;// Flattened leftTreeNode*constright=root->right;// Flattened rightroot->left=nullptr;root->right=left;// Connect the original right subtree// To the end of new right subtreeTreeNode*rightmost=root;while(rightmost->right)rightmost=rightmost->right;rightmost->right=right;}};
classSolution{publicvoidflatten(TreeNoderoot){if(root==null)return;flatten(root.left);flatten(root.right);TreeNodeleft=root.left;// Flattened leftTreeNoderight=root.right;// Flattened rightroot.left=null;root.right=left;// Connect the original right subtree// To the end of new right subtreeTreeNoderightmost=root;while(rightmost.right!=null)rightmost=rightmost.right;rightmost.right=right;}}
classSolution:defflatten(self,root:Optional[TreeNode])->None:ifnotroot:returnself.flatten(root.left)self.flatten(root.right)left=root.left# Flattened leftright=root.right# Flattened rightroot.left=Noneroot.right=left# Connect the original right subtree# To the end of new right subtreerightmost=rootwhilerightmost.right:rightmost=rightmost.rightrightmost.right=right