博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Flatten Binary Tree to Linked List
阅读量:7060 次
发布时间:2019-06-28

本文共 1916 字,大约阅读时间需要 6 分钟。

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 利用前序遍历解决的方法实现
void flatten(TreeNode* root) {    if (root == nullptr)        return;    stack
sta; sta.push(root); TreeNode* lastRoot = root; while (!sta.empty()) { root = sta.top(); if (lastRoot != root->right) { if (lastRoot != root->left) { if (root->left != nullptr) { sta.push(root->left); continue; } } else { TreeNode* tempNode = root->right; root->right = lastRoot; root->left = nullptr; TreeNode* endNode = lastRoot; while (endNode->right != nullptr) endNode = endNode->right; endNode->right = tempNode; } if (root->right != nullptr) { sta.push(root->right); continue; } } lastRoot = root; sta.pop(); }}

不使用遍历的方法,即不使用栈解决的方法

void flatten(TreeNode *root) {    TreeNode*now = root;    while (now)    {        if (now->left)        {            //Find current node's prenode that links to current node's right subtree            TreeNode* pre = now->left;            while (pre->right)            {                pre = pre->right;            }            pre->right = now->right;            //Use current node's left subtree to replace its right subtree(original right             //subtree is already linked by current node's prenode            now->right = now->left;            now->left = NULL;        }        now = now->right;    }}

 

 

转载于:https://www.cnblogs.com/sdlwlxf/p/5224557.html

你可能感兴趣的文章
ASP_NET Global_asax详解
查看>>
hdu2067 小兔的棋盘 DP/数学/卡特兰数
查看>>
Ubuntu文件模式之设定笔记
查看>>
转:IIS虚拟目录实现与文件服务器网络驱动器映射共享
查看>>
解决 MariaDB无密码就可以登录的问题
查看>>
AP_MergeSql
查看>>
2016/4/3 总结作业
查看>>
用node.js写一个jenkins发版脚本
查看>>
iOS开发-UITabBarController详解
查看>>
算法-动态连通性
查看>>
webBrowser控件
查看>>
layui 表格组件不能访问连续的属性的解决办法
查看>>
windows server 2003 原版 安装 php+mysql+apache 教程
查看>>
【BZOJ1930】【SHOI2003】吃豆豆
查看>>
PostgreSQL 10.0 压缩版的 pgAdmin 不能用的问题
查看>>
动态最小生成树讲解
查看>>
find命令
查看>>
Windows和Mac下安装Beautiful Soup
查看>>
Mac 配置android环境变量
查看>>
SkyLine二次开发——解决在web页面启动时自动运行TerraExplorer的问题
查看>>