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

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

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.

 

C++代码如下:

#include
#include
#include
#include
using namespace std;//Definition for binary treestruct 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; vector
vec; preorder(root,vec); TreeNode *tmp=root; size_t i; for(i=1; i
left=NULL; tmp->right=vec[i]; tmp=tmp->right; } tmp->left=tmp->right=NULL; } void preorder(TreeNode *root,vector
&vec) { stack
s; while(root||!s.empty()) { while(root) { vec.push_back(root); s.push(root); root=root->left; } if(!s.empty()) { root=s.top(); s.pop(); root=root->right; } } } void createTree(TreeNode *&root) { int i; cin>>i; if(i!=0) { root=new TreeNode(i); if(root==NULL) return; createTree(root->left); createTree(root->right); } }};int main(){ Solution s; TreeNode *root; s.createTree(root); s.flatten(root); while(root) { cout<
val<<" "; root=root->right; }}

运行结果:

提交到leetcode时,一直报错,开始不太了解,后来才发现是因为左指针一直没有设为NULL.

class Solution {public:    void flatten(TreeNode *root)    {        if(root==NULL)            return;        vector
vec; preorder(root,vec); TreeNode *tmp=root; size_t i; for(i=1; i
right=vec[i]; tmp=tmp->right; } tmp->right=NULL; } void preorder(TreeNode *root,vector
&vec) { stack
s; while(root||!s.empty()) { while(root) { vec.push_back(root); s.push(root); root=root->left; } if(!s.empty()) { root=s.top(); s.pop(); root=root->right; } } } void createTree(TreeNode *&root) { int i; cin>>i; if(i!=0) { root=new TreeNode(i); if(root==NULL) return; createTree(root->left); createTree(root->right); } }};

注意,最后的指针哪些该设置为空。

转载地址:http://aptyl.baihongyu.com/

你可能感兴趣的文章
JS设置cookie、读取cookie、删除cookie
查看>>
我的博客园的CSS和html设置
查看>>
数论基础(维诺格拉多夫著,裘光明译) 勘误
查看>>
vue-cookies的使用
查看>>
Code Signal_练习题_Make Array Consecutive2
查看>>
双向循环链表 初始化 插入 删除
查看>>
C#设计模式:职责链模式(Chain of Responsibility)
查看>>
Knockout.js随手记(2)
查看>>
条件注释判断IE浏览器
查看>>
Hibernate,删除对象时错误。
查看>>
C#中Cookies的读取
查看>>
冬季养生进补20招
查看>>
20179311《网络攻防实践》第四周作业
查看>>
《thinking in Java》第三章 控制程序流程
查看>>
《游戏引擎架构》笔记一
查看>>
pythoy-生成器
查看>>
Redis 分布式锁进化史
查看>>
Java 集合系列05之 LinkedList详细介绍(源码解析)和使用示例
查看>>
Codeforces Round #547 (Div. 3) D
查看>>
kali linux fuzz工具集简述
查看>>