1 / \ 2 5 / \ \ 3 4 6
1 \ 2 \ 3 \ 4 \ 5 \ 6
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
本题采用递归的方法解决,关键是要知道由左子树转化的链表的头和尾,以及由右子树转化的链表的头和尾。头一定是二叉树的根节点,尾是右子树的尾(如果右子树不空)或者(如果右子树空,左子树不空)或者根(如果左右子树都是空)。
void flatten(TreeNode *root) { // main function if(root == NULL) return; ConvertToLink(root); } TreeNode* ConvertToLink(TreeNode* root) // utility function {// return value is the tail of the linked list if(root==NULL) return NULL; TreeNode* leftLinkTail = ConvertToLink(root->left); // tail of left linked list TreeNode* rightLinkTail = ConvertToLink(root->right); // tail of left linked list if(leftLinkTail != NULL) { leftLinkTail->right = root->right; root->right = root->left; } root->left = NULL; if(rightLinkTail!= NULL) return rightLinkTail; else if(leftLinkTail != NULL) return leftLinkTail; else return root; }