leetcode114.二叉树展开为链表

参考:
https://www.cnblogs.com/ariel-dreamland/p/9162548.html

题目解读:
(1)展开后应该为单向链表;
(2)展开后节点左子树为空,右子树指向下一个元素
(3)链表顺序为前序遍历序列

// Recursion
 2 class Solution {
 3 public:
 4     void flatten(TreeNode *root) {
 5         if (!root) return;
 6         if (root->left) flatten(root->left); //转换左子树
 7         if (root->right) flatten(root->right);
 8         TreeNode *tmp = root->right; //将左子树部分插入到根节点和右子树之间,并将根节点左子树设为nullptr.注意考虑边界条件,即一个节点的情况,即代码中只可以出现root->left或者right.不可以出现p=root->left,p->right这种代码
 9         root->right = root->left;
10         root->left = NULL;
11         while (root->right) root = root->right;
12         root->right = tmp;
13     }
14 };
// Non-recursion
 2 class Solution {
 3 public:
 4     void flatten(TreeNode *root) {
 5         TreeNode *cur = root;
 6         while (cur) { 
 7             if (cur->left) { //如果有左节点,就将左子树部分插入到当前节点和右子树之间,并将左子树设为nullptr
 8                 TreeNode *p = cur->left;
 9                 while (p->right) p = p->right;
10                 p->right = cur->right;
11                 cur->right = cur->left;
12                 cur->left = NULL;
13             }
14             cur = cur->right; //下一步
15         }
16     }
17 };

猜你喜欢

转载自blog.csdn.net/aikudexue/article/details/89472322