LeetCode(114)Flatten Binary Tree to Linked List

本文介绍了一种将二叉树转换为链表的方法,重点在于利用栈实现前序遍历的同时完成树的展平操作。文章通过具体实例展示了如何确保每个节点的右子节点指向下一个前序遍历节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目分析

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

Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.


分析如下:

因为最后flatten的结果是树的前序遍历的结果,所以考虑一边进行前序遍历,一边进行flatten转化.


代码如下:

//48ms过大集合
/**
 * 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;
        stack<TreeNode*> node_stack;
        node_stack.push(root);
        TreeNode* new_root=NULL;
        TreeNode* cur=NULL;
        TreeNode* next=NULL;
        while(!node_stack.empty()){
            cur=node_stack.top();
            node_stack.pop();
            if(cur->right!=NULL)
                node_stack.push(cur->right);
            if(cur->left!=NULL)
                node_stack.push(cur->left);
            if(new_root==NULL){
                new_root=cur;
                next=cur;
                cur->left=NULL;
            } else {
                next->right=cur;
                next->left=NULL;
                next=cur;
            }
        }
        root=new_root;
    }
};

小结:

(1) 逻辑很重要,在while循环体中,应该先把cur->right, cur->left压栈,再去进行flatten。如果颠倒了顺序,就会在flatten时破坏一些还没有被处理的节点,这些节点被压栈,随后就会发生错误。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值