[LeetCode] Flatten Binary Tree to Linked List
http://oj.leetcode.com/problems/flatten-binary-tree-to-linked-list/
分类讨论, 很简单, 注意下给左子树赋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 // IMPORTANT: Please reset any member data you declared, as 14 // the same Solution instance will be reused for each test case. 15 if (root == NULL) return; 16 if (root->left == NULL && root->right == NULL) { 17 return; 18 } else if (root->left == NULL) { 19 flatten(root->right); 20 } else if (root->right == NULL) { 21 root->right = root->left; 22 root->left = NULL; 23 flatten(root->right); 24 } else { 25 flatten(root->left); 26 flatten(root->right); 27 TreeNode* p = root->left; 28 while (p->right) { 29 p = p->right; 30 } 31 p->right = root->right; 32 root->right = root->left; 33 root->left = NULL; 34 } 35 } 36 };