Flatten Binary Tree to Linked List:

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

这题的主要难点是“in-place”。因为这个flatten的顺序是中、左、右(相当于中序遍历),所以右子树总是在最后的,所以解题思想就是,每次把当前节点的右子树放到左子树的最右边。
图示例:
[LeetCode]Flatten Binary Tree to Linked List题解(二叉树)
c++实现代码如下:

/**
 * 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:
    vector<int> re;
    void flatten(TreeNode* root) {
        TreeNode *now = root;
        while(now){
            if(now->left){
                TreeNode *pre = now->left;
                //找到左子树的最右节点
                while(pre->right){
                    pre = pre->right;
                }
                //now的右节点放到左子树的最右节点
                //now的右节点更新为左节点,左节点赋为NULL
                pre->right = now->right;
                now->right = now->left;
                now->left = NULL;
            }
            //now不断向右向下
            now = now->right;
        }
        return;
    }
};

相关文章:

  • 2021-12-17
  • 2021-06-18
  • 2021-06-17
  • 2022-12-23
  • 2021-11-04
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-05-31
  • 2021-09-15
  • 2021-05-27
  • 2021-07-14
  • 2022-02-09
相关资源
相似解决方案