leetcode - 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 a binary tree node. * 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){ if(root->left != NULL){ flatten(root->left); TreeNode* tp = root->left;// tail node while(tp->right != NULL){ tp = tp->right; } tp->right = root->right; root->right = root->left; root->left = NULL; } flatten(root->right); } } };
思路:
1 判断root是否为NULL;
2 判断左子树是否为NULL;
2.1 对左子树展开;
2.2 找到左子树中最右的节点,即尾节点;
2.3 将尾节点右指针指向右子树;
2.4 将根节点的右指针指向左子树;
2.5 将根节点的左指针指向NULL;
3 判断右子树是否为NULL;
对右子树展开。
其他:http://www.2cto.com/kf/201409/331296.html