[leetcode] Flatten Binary Tree to Linked List

本文详细介绍了如何通过递归中序遍历来平铺二叉树为链表,包括解决unsigned int a = 0时使用a-1可能引发的问题,并提供了完整的C++代码实现。

摘要生成于 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
对了,做这道题的时候发现一个小问题:unsigned int a=0,这个时候如果用a-1的话会得到一个大整数,不是-1,会导致循环出问题。

class Solution {
public:
    void flatten(TreeNode *root) {
		// Start typing your C/C++ solution below
		// DO NOT write int main() function
		vector<TreeNode*> path;
		_preorder(root,path);
		int length=path.size();
		for(int i=0 ; i<length-1 ; i++){
			path[i]->right=path[i+1];
			path[i]->left=NULL;
		}

	}
	void _preorder(TreeNode *root, vector<TreeNode*>& path){
		if(root==NULL)
			return;
		path.push_back(root);
		if(root->left)
			_preorder(root->left,path);
		if(root->right)
			_preorder(root->right,path);
	}
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值