LeetCode OJ - Flatten Binary Tree to Linked List

来源:互联网 发布:社区巡展 知乎 编辑:程序博客网 时间:2024/06/05 18:11

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

click to show hints.

分析:root -> left -> right 其中root->right一定是指向原来的左子树,而原来的左子树最后一个元素指向原来的右子树,第一次得到下面的结果


接着以2为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 ;        while(root) {            if(root->left) {                TreeNode *p = root->left;                //寻找左子树“最后”一个节点                while(p->right) p = p->right;                //根、左子树、右子树的连接                p->right = root->right;                root->right = root->left;                root->left = NULL;            }                        root = root->right;        }    } };

下面是递归代码:

/** * 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 ;        Adjust(root);    }         void Adjust(TreeNode * root) {        if(root == NULL) return ;                if(root->left) {            TreeNode *p = root->left;            //寻找左子树“最后”一个节点            while(p->right) p = p->right;            //根、左子树、右子树的连接            p->right = root->right;            root->right = root->left;            root->left = NULL;        }                Adjust(root->right);    }};








0 0
原创粉丝点击