Unfortunately this is not a correct solution. The problem does not explicitly talk about the order in which nodes need to appear in the final list, and I was assuming flattening with postorder to the left would work. But I was mistaken 😲!
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ classSolution { TreeNode *postorder(TreeNode* root){ if (root == nullptr) return root; /* base case - if leaf node, then return itself */ if (!root->left && !root->right) return root;
TreeNode* leaf = postorder(root->left);
/* Move my right subtree into the left leaf node */ if (root->right) { postorder(root->right); if (leaf) leaf->left = root->right; else root->left = root->right; root->right = nullptr; }
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ classSolution { TreeNode *postorder(TreeNode* root){ if (root == nullptr) return root; /* base case - if leaf node, then return itself */ if (!root->left && !root->right) return root;
TreeNode* left_leaf = postorder(root->left);
/* Move my left subtree into the right */ TreeNode* right_leaf = postorder(root->right); if (right_leaf) { right_leaf->right = root->left; } else { root->right = root->left; } root->left = nullptr;
// if we have a left leaf then attach left subtree // in between root and right subtree if (left_leaf) { left_leaf->right = root->right; root->right = root->left; root->left = nullptr; }
/* right leaf is the the only leaf remaining, return this */ return right_leaf;
This solution does not account for the fact that when right subtree of a given root is null then the resultant right leaf will actually be the left leaf.
classSolution { TreeNode *traverse(TreeNode *root){ if (root == nullptr) return root; /* base case - if leaf node, then return itself */ if (!root->left && !root->right) return root;
// if we have a left leaf then attach left subtree // in between root and right subtree if (left_leaf) { left_leaf->right = root->right; root->right = root->left; root->left = nullptr; }
/* if right leaf was null then when we return leaf leaf */ return (right_leaf?right_leaf:left_leaf);