将 C++ 中的二叉树展开为链表
假设我们有二叉树,必须在原地将其展开为链表。因此,如果是这样的树-
输出树为-
要解决这个问题,我们将按照以下步骤进行-
ser prev := null
定义一个递归函数 solve(),它将根作为输入。
如果根为空,则返回
solve(根的右边)
solve(根的左边)
根的右边 := prev,根的左边 := null
prev := root
让我们查看以下实现,以更好地理解代码-
示例
#include <bits/stdc++.h> using namespace std; class TreeNode{ public: int val; TreeNode *left, *right; TreeNode(int data){ val = data; left = NULL; right = NULL; } }; void insert(TreeNode **root, int val){ queue<TreeNode*> q; q.push(*root); while(q.size()){ TreeNode *temp = q.front(); q.pop(); if(!temp->left){ if(val != NULL) temp->left = new TreeNode(val); else temp->left = new TreeNode(0); return; }else{ q.push(temp->left); } if(!temp->right){ if(val != NULL) temp->right = new TreeNode(val); else temp->right = new TreeNode(0); return; }else{ q.push(temp->right); } } } TreeNode *make_tree(vector<int> v){ TreeNode *root = new TreeNode(v[0]); for(int i = 1; i<v.size(); i++){ insert(&root, v[i]); } return root; } class Solution { public: TreeNode* prev = NULL; void flatten(TreeNode* root) { if(!root) return; flatten(root->right); flatten(root->left); root->right = prev; root->left = NULL; prev = root; } }; main(){ vector<int> v = {1,2,5,3,4}; TreeNode *root = make_tree(v); Solution ob; (ob.flatten(root)); TreeNode *ptr = root; while(ptr != NULL && ptr->val != 0){ cout << ptr->val << ", "; ptr = ptr->right; } }
输入
[1,2,5,3,4]
输出
1, 2, 3, 4, 5,
广告