抚顺市 网站建设,怎么导入模板到wordpress,wordpress 学习插件,友情链接怎么互换思路#xff1a; 根据二叉树前序遍历#xff1a;根-左子树-右子树#xff1b;要按照前序遍历将二叉树展开#xff0c;则遍历节点右子树需要挂载到左子树“最右”节点右子树上#xff1b;则当前节点 current 左子树 next current-left 的最右节点 rightmost #xff…思路 根据二叉树前序遍历根-左子树-右子树要按照前序遍历将二叉树展开则遍历节点右子树需要挂载到左子树“最右”节点右子树上则当前节点 current 左子树 next current-left 的最右节点 rightmost TreeNode* rightmost next;
while (rightmost-right ! nullptr) {rightmost rightmost-right;
} 将当前节点右子树挂载到左子树“最右”节点的右子树上rightmost-right current-right;则当前节点 current 展开完成将其左子树按照要求置 nullptr右子树挂载其左子树节点current-left nullptr;current-right next;迭代下一个需要展开的节点对应的树
/*** 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;}}
};