题目链接
Flatten Binary Tree to Linked List - LeetCode
注意点
- 不要访问空结点
- val会有负值
解法
解法一:递归,DFS。先找到最低一层的最左子节点,然后回到其父节点,把其父节点和右子节点断开,将原左子结点连上父节点的右子节点上,然后再把原右子节点连到新右子节点的右子节点上,然后再回到上一父节点做相同操作。
/**
* 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) return;
if(root->left) flatten(root->left);
if(root->right) flatten(root->right);
TreeNode* temp = root->right;
root->right = root->left;
root->left = NULL;
while(root->right) root = root->right;
root->right = temp;
}
};
解法二:非递归。从根节点开始出发,先检测其左子结点是否存在,如存在则将根节点和其右子节点断开,将左子结点及其后面所有结构一起连到原右子节点的位置,把原右子节点连到元左子结点最后面的右子节点之后。
/**
* 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) return;
TreeNode* temp = root;
while(temp)
{
if(temp->left)
{
TreeNode* p = temp->left;
while(p->right) p = p->right;
p->right = temp->right;
temp->right = temp->left;
temp->left = NULL;
}
temp = temp->right;
}
}
};