标签:c++ leetcode tree recursion

114 Flatten Binary Tree to Linked List
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
/**
* 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* flattenUtil(TreeNode *root)
{
if( root==NULL )
return NULL;
TreeNode *left = root->left;
TreeNode *right = root->right;
root->left = NULL;
if(left)
{
root->right = left;
root = flattenUtil(left); //root指针指向left,即next
}
if(right)
{
root->right = right;
root = flattenUtil(right); //root指针指向right,即next
}
return root;
}
void flatten(TreeNode *root) {
flattenUtil(root);
}
};leetcode_114_Flatten Binary Tree to Linked List
标签:c++ leetcode tree recursion
原文地址:http://blog.csdn.net/keyyuanxin/article/details/44216837