忘记加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 }
Java
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public void flatten(TreeNode root) { 12 Stack<TreeNode> st = new Stack<TreeNode>(); 13 if (root == null) return; 14 while (root != null) 15 { 16 if (root.left != null) 17 { 18 if (root.right != null) st.push(root.right); 19 root.right = root.left; 20 root.left = null; 21 root = root.right; 22 } 23 else 24 { 25 if (root.right == null && st.empty() == false) 26 { 27 root.right = st.peek(); 28 st.pop(); 29 } 30 root = root.right; 31 } 32 } 33 } 34 }