LeetCode: Flatten Binary Tree to Linked List

忘记加tmp->left = NULL了,少数次改

 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         // Start typing your C/C++ solution below

14         // DO NOT write int main() function

15         stack<TreeNode *> S;

16         if (!root) return;

17         TreeNode *tmp = root;

18         while (tmp) {

19             if (tmp->right) S.push(tmp->right);

20             if (tmp->left) {

21                 tmp->right = tmp->left;

22                 tmp->left = NULL;

23                 tmp = tmp->right;

24             }

25             else {

26                 if (!S.empty()) {

27                     tmp->right = S.top();

28                     tmp = tmp->right;

29                     S.pop();

30                 }

31                 else break;

32             }

33         }

34         return;

35     }

36 };

 贴上另外一段

 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         // Start typing your C/C++ solution below

14         // DO NOT write int main() function

15         stack<TreeNode*> S;

16         while (root) {

17             if (root->left) {

18                 if (root->right) S.push(root->right);

19                 root->right = root->left;

20                 root->left = NULL;

21             }

22             else if (!root->right && !S.empty()) {

23                 root->right = S.top();

24                 S.pop();

25             }

26             root = root->right;

27         }

28     }

29 };

 C#

 1 /**

 2  * Definition for a binary tree node.

 3  * public class TreeNode {

 4  *     public int val;

 5  *     public TreeNode left;

 6  *     public TreeNode right;

 7  *     public TreeNode(int x) { val = x; }

 8  * }

 9  */

10 public class Solution {

11     public void Flatten(TreeNode root) {

12         Stack<TreeNode> S = new Stack<TreeNode>();

13         while (root != null) {

14             if (root.left != null) {

15                 if (root.right != null) S.Push(root.right);

16                 root.right = root.left;

17                 root.left = null;

18             }

19             else if (root.right == null && S.Count != 0) {

20                 root.right = S.Peek();

21                 S.Pop();

22             }

23             root = root.right;

24         }

25     }

26 }
View Code

 

你可能感兴趣的:(LeetCode)