[leetCode]Flatten Binary Tree to Linked List
递归的思想,左子树整理成一条链,右子树整理成一条链,然后左子树的尾节点链上右子树的头节点就好了
1 #include <iostream> 2 using namespace std; 3 struct TreeNode { 4 int val; 5 TreeNode *left; 6 TreeNode *right; 7 TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 }; 9 class Solution { 10 public: 11 void flatten(TreeNode *root) { 12 if(root == NULL) return; 13 flattenTree(root); 14 } 15 TreeNode *flattenTree(TreeNode *root){ 16 if(root == NULL) return NULL; 17 if(root->left == NULL && root->right == NULL) return root; 18 TreeNode *lefthead,*righthead; 19 righthead = lefthead = NULL; 20 if(root->left != NULL) lefthead = flattenTree(root->left); 21 if(root->right != NULL) righthead = flattenTree(root->right); 22 if(lefthead == NULL) root->right = righthead; 23 if(righthead == NULL) root->right = lefthead; 24 if(lefthead != NULL && righthead != NULL){ 25 root->right = lefthead; 26 TreeNode *leftTail = getTail(lefthead); 27 leftTail->right = righthead; 28 } 29 root->left = NULL; 30 return root; 31 } 32 TreeNode *getTail(TreeNode *root){ 33 if(root == NULL) return NULL; 34 while(root->right != NULL) root = root->right; 35 return root; 36 } 37 };
艰难的成长