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
Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
思路:给定一个二叉树,将它变成一个类似上面那样的链表,而且操作要原地进行.递归处理之后,把右子树连接到处理后的左子树上,然后在把左子树改成右子树,然后再把左子树设为NULL;
/** * 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 flattree(TreeNode *root) { if(root==NULL) return; flattree(root->left); flattree(root->right); TreeNode *cur=root; if(cur->left==NULL) return; else cur=cur->left; while(cur->right!=NULL) cur=cur->right; cur->right=root->right; root->right=root->left; root->left=NULL; } void flatten(TreeNode *root) { flattree(root); } };
循环方法:
/** * 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) { if(root==NULL) return ; TreeNode *pPre; while(root) { if(root->left) { pPre=root->left; while(pPre->right) pPre=pPre->right; pPre->right=root->right; root->right=root->left; root->left=NULL; } root=root->right; } } };