/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void flatten(TreeNode *root) { flattenHelper(root); } TreeNode * flattenHelper(TreeNode * root) { if(root == NULL) { return root; } TreeNode * leftFlatten = flattenHelper(root->left); TreeNode * rightFlatten = flattenHelper(root->right); if(leftFlatten != NULL) { root->right = leftFlatten; TreeNode * p = root; while(p->right != NULL) { p = p->right; } p->right = rightFlatten; } root->left = NULL; //DON'T FORGET TO CLEAR LEFT TREE!!!!! return root; } };
4/20/2014
Leetcode -- Flatten Binary Tree to Linked List
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment