博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode]Binary Tree Inorder Traversal
阅读量:4150 次
发布时间:2019-05-25

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

struct TreeNode {	int val;	TreeNode *left;	TreeNode *right;	TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution {//recursive to iterative, we always need stack//thought of the stack of recursive function, then we can come//up with the iterative version easily. //turn recursive into iterative//if(root), s.push(root)(save the scene, just like function stack), root=root->left(get to the next level, called by function itself)//if(!root), set root=s.top()(get the nearest scene) visit its value and then set root=root->right(get to the next level, called by function itself)public:	vector
inorderTraversal(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function vector
res; stack
s; TreeNode* current = root; while (true) { //add all left in if(current) { s.push(current); current = current->left; } else { if(s.empty()) break; current = s.top(); s.pop(); res.push_back(current->val); current = current->right; } } return res; }};

second time

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    vector
inorderTraversal(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function stack
nodeS; TreeNode* cur = root; vector
ans; while(true) { if(cur != NULL) { nodeS.push(cur); cur = cur->left; } else { if(!nodeS.empty()) { ans.push_back(nodeS.top()->val); cur = nodeS.top()->right; nodeS.pop(); } else break;//terminate case } } return ans; }};

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

你可能感兴趣的文章
python循环语句与C语言的区别
查看>>
vue 项目中图片选择路径位置static 或 assets区别
查看>>
vue项目打包后无法运行报错空白页面
查看>>
Vue 解决部署到服务器后或者build之后Element UI图标不显示问题(404错误)
查看>>
element-ui全局自定义主题
查看>>
facebook库runtime.js
查看>>
vue2.* 中 使用socket.io
查看>>
openlayers安装引用
查看>>
js报错显示subString/subStr is not a function
查看>>
高德地图js API实现鼠标悬浮于点标记时弹出信息窗体显示详情,点击点标记放大地图操作
查看>>
初始化VUE项目报错
查看>>
vue项目使用安装sass
查看>>
在osg场景中使用GLSL语言——一个例子
查看>>
laravel 修改api返回默认的异常处理
查看>>
laravel事务
查看>>
【JavaScript 教程】浏览器—History 对象
查看>>
这才是学习Vite2的正确姿势!
查看>>
7 个适用于所有前端开发人员的很棒API,你需要了解一下
查看>>
49个在工作中常用且容易遗忘的CSS样式清单整理
查看>>
20种在学习编程的同时也可以在线赚钱的方法
查看>>