NC332. 二叉树展开为单链表
描述
示例1
输入:
{1,2,3,4,8}
输出:
{1,#,2,#,4,#,8,#,3}
示例2
输入:
{0}
输出:
{0}
C++ 解法, 执行用时: 46ms, 内存消耗: 9516KB, 提交时间: 2022-06-20
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 */ void expandTree(TreeNode* root) { // write code here while(root){ if(root->left&&root->right){ TreeNode *t=root->left; while(t->right) t=t->right; t->right=root->right; root->right=root->left; root->left=NULL; } else if(root->left){ root->right=root->left; root->left=NULL; } root=root->right; } } };
C 解法, 执行用时: 48ms, 内存消耗: 9480KB, 提交时间: 2022-06-23
void expandTree(struct TreeNode* root ) { while (root) { if (root->left && root->right) { struct TreeNode* t = root->left; while (t->right) t = t->right; t->right = root->right; root->right = root->left; root->left = NULL; } else if (root->left) { root->right = root->left; root->left = NULL; } root = root->right; } }
C++ 解法, 执行用时: 48ms, 内存消耗: 9600KB, 提交时间: 2022-07-02
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 */ void expandTree(TreeNode* root) { if (!root) return; TreeNode *node = root; TreeNode *prev = root; stack<TreeNode *> st; st.push(node); while (!st.empty()) { node = st.top(); st.pop(); if (node->right) st.push(node->right); if (node->left) st.push(node->left); if (node != prev) { prev->right = node; prev = node; } prev->left = nullptr; } prev->right = nullptr; } };
C++ 解法, 执行用时: 49ms, 内存消耗: 9472KB, 提交时间: 2022-06-23
class Solution { public: void expandTree(TreeNode* root) { while (root) { if (root->left && root->right) { TreeNode* t = root->left; while (t->right) t = t->right; t->right = root->right; root->right = root->left; root->left = NULL; } else if (root->left) { root->right = root->left; root->left = NULL; } root = root->right; } } };
C++ 解法, 执行用时: 49ms, 内存消耗: 9472KB, 提交时间: 2022-05-24
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 */ void expandTree(TreeNode* x) { while (x) { if (x->left && x->right) { TreeNode * t = x->left; while (t->right) t = t->right; t->right = x->right; x->right = x->left; x->left = NULL; } else if (x->left) { x->right = x->left; x->left = NULL; } x = x->right; } } };