按照前序遍历的顺序把树用right连起来。
本来想了半天,一点思路都没有,总觉得Inplace的解法一般都非常巧妙。
后来我突发灵感,决定用一个变量记录当前访问到哪个点,真是太机智了~~
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 void flatten(TreeNode *root) { 13 now = NULL; 14 findRes(root); 15 } 16 private: 17 TreeNode * now; 18 void findRes(TreeNode *root) { 19 if (root == NULL) { 20 return; 21 } 22 findRes(root->right); 23 findRes(root->left); 24 root->left = NULL; 25 root->right = now; 26 now = root; 27 } 28 };
一次AC之后看了题解,发现大家的思路差别好大!其中迭代的那个版本感觉很清晰。又写了一遍,同样是一次AC。
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 void flatten(TreeNode *root) { 13 if (root == NULL) { 14 return; 15 } 16 stack<TreeNode*> s; 17 s.push(root); 18 while (!s.empty()) { 19 TreeNode * now = s.top(); 20 s.pop(); 21 if (now->right != NULL) { 22 s.push(now->right); 23 } 24 if (now->left != NULL) { 25 s.push(now->left); 26 } 27 now->left = NULL; 28 if (!s.empty()) { 29 now->right = s.top(); 30 } 31 } 32 } 33 };
[Leetcode][Tree][Flatten Binary Tree to Linked List ]
时间: 2024-10-06 16:00:51