LeetCode—114. Flatten Binary Tree to Linked List

Given a binary tree, flatten it to a linked list in-place.

For example, given the following tree:

        1

       / \

   2       5

  / \            \

3    4            6

The flattened tree should look like:

1

\

  2

  \

    3

    \

      4

      \

        5

        \

          6


将一棵二叉树转化为linked list

前序遍历,将root的右节点放置到左节点最后一个右子节点下方,递归遍历。


/**

* 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) {

        while(root){

            TreeNode* cur;

            if(root->left){

                cur = root->left;

                while(cur->right){

                    cur = cur->right;

                }

                cur->right = root->right;

                root->right = root->left;

                root->left = NULL;

            }

            root = root->right;

        }

    }

};

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容