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
分析:最后生成的类似链表的树状结构就是树的前序遍历。关于树结构的编程用递归都很好写。我们采用类似前序遍历的方法,先把树右节点改为左侧的前序遍历,然后再找到左侧的最后一个节点,右节点链接到右侧的前序遍历。
特别注意边界条件,特别是左树为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 flatten(TreeNode *root) { if(root==NULL) return; TreeNode* KeepRight = root->right;//记录节点 root->right = root->left; TreeNode* KeepLeft = root->left; TreeNode* pre = root; root->left = NULL; //左侧断链 flatten(KeepLeft); while(pre->right!=NULL)//找到左侧最后一个节点,注意左侧为NULL的情况 pre = pre->right; pre->right = KeepRight; flatten(KeepRight); } };