- 思路:
-
根据二叉树前序遍历:根-左子树-右子树;
-
要按照前序遍历将二叉树展开,则遍历节点右子树需要挂载到左子树"最右"节点右子树上;
-
则当前节点 current 左子树 next = current->left 的最右节点 rightmost :
*cppTreeNode* rightmost = next; while (rightmost->right != nullptr) { rightmost = rightmost->right; }
-
将当前节点右子树挂载到左子树"最右"节点的右子树上:rightmost->right = current->right;
-
则当前节点 current 展开完成,将其左子树按照要求置 nullptr,右子树挂载其左子树节点:current->left = nullptr;current->right = next;
-
迭代下一个需要展开的节点对应的树;
-
cpp
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void flatten(TreeNode* root) {
TreeNode *current = root;
while (current != nullptr) {
if (current->left != nullptr) {
TreeNode* next = current->left;
TreeNode* rightmost = next;
while (rightmost->right != nullptr) {
rightmost = rightmost->right;
}
rightmost->right = current->right;
current->left = nullptr;
current->right = next;
}
current = current->right;
}
}
};