欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Leetcode Flatten Binary Tree to Linked List

程序员文章站 2022-04-27 08:53:06
...

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) {
        TreeNode* now = root;
        while(now)
        {
            if(now->left)
            {
                TreeNode* pre = now->left;
                while(pre->right != NULL)
                    pre = pre->right;
                pre->right = now->right;
                now->right = now->left;
                now->left = NULL;
            }
            now = now->right;
        }
    }
};

Leetcode Flatten Binary Tree to Linked List

相关标签: leetcode