class Solution {
public:
void flatten(TreeNode* root) {
if(root==NULL) return;
build(root);
return;
}
TreeNode * build(TreeNode * root){
if(root->left==NULL && root->right==NULL) return root;
TreeNode * left=NULL;
TreeNode * right=NULL;
if(root->left) left=build(root->left);
if(root->right) right=build(root->right);
if(root->left) {
root->right = left;
while(left->right!=NULL){
left = left->right;
}
}
if(root->left) left->right = right;
else if(root->right) root->right = right;//(1)错,少else
root->left=NULL;//(2)错,左孩子没有置空
return root;
}
};
这题看着简单,容易有想不到的点,(1)当左孩子不为空的时候,当前left表示的是左孩子的最后一个非空节点,那么left的right置为右孩子,这个时候我们知道root的right已经指向其左孩子了,所以要加一个else判断,即左孩子空,那么直接将root-right置为right;(2)表示成单向链表,那么左孩子都要置为空,这里很重要。