Flatten Binary Tree to Linked List
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
TreeNode* helper(TreeNode* A) { TreeNode* res = A; if(A->left == NULL and A->right == NULL) return res; if(A->left == NULL and A->right != NULL) return helper(res->right); if(A->left != NULL and A->right == NULL) { swap(res->left, res->right); return helper(res->right); } TreeNode* l = A->left; TreeNode* r = A->right; res->right = res->left = NULL; res->right = l; TreeNode* leftTail = helper(l); leftTail->right = r; return helper(r); } TreeNode* Solution::flatten(TreeNode* A) { helper(A); return A; }
|