Created
January 7, 2013 14:39
-
-
Save pdu/4475421 to your computer and use it in GitHub Desktop.
Given a binary tree, flatten it to a linked list in-place. http://leetcode.com/onlinejudge
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Definition for binary tree | |
| * struct TreeNode { | |
| * int val; | |
| * TreeNode *left; | |
| * TreeNode *right; | |
| * TreeNode(int x) : val(x), left(NULL), right(NULL) {} | |
| * }; | |
| */ | |
| class Solution { | |
| public: | |
| TreeNode* flatten_(TreeNode* root) { | |
| if (root->left == NULL && root->right == NULL) | |
| return root; | |
| if (root->left == NULL) | |
| return flatten_(root->right); | |
| if (root->right == NULL) { | |
| TreeNode* tmp = flatten_(root->left); | |
| root->right = root->left; | |
| root->left = NULL; | |
| return tmp; | |
| } | |
| TreeNode* tmp = flatten_(root->left); | |
| tmp->right = root->right; | |
| root->right = root->left; | |
| root->left = NULL; | |
| return flatten_(root->right); | |
| } | |
| void flatten(TreeNode *root) { | |
| if (root == NULL) | |
| return; | |
| flatten_(root); | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment