[leetcode] Binary Tree Inorder Traversal
来源:互联网 发布:好看的青春爱情网络剧 编辑:程序博客网 时间:2024/06/05 15:54
Binary Tree Inorder Traversal
使用递归
class Solution {private: vector<int> res;public: vector<int> inorderTraversal(TreeNode *root) { if (root!=NULL) { inorderTraversal(root->left); res.push_back(root->val); inorderTraversal(root->right); } return res; }};
非递归,使用栈模拟
#include <iostream>#include <vector>#include <stack>#include <list>#include <queue>using namespace std;/** * Definition for binary tree */struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution {private: vector<int> res; stack<TreeNode*> stk;public: vector<int> inorderTraversal(TreeNode *root) { if (root==NULL) { return res; } stk.push(root); while (!stk.empty()) { TreeNode *tmp=stk.top(); if (tmp->left==NULL&&tmp->right==NULL) { stk.pop(); res.push_back(tmp->val); }else{ stk.pop();//通用模板,调整入栈顺序,即可实现先序、中序、后序遍历 if (tmp->right!=NULL) { stk.push(tmp->right); } stk.push(tmp); if (tmp->left!=NULL) { stk.push(tmp->left); } tmp->left=tmp->right=NULL; } } return res; }};
参考:
Binary Tree Inorder Traversal
0 0
- LeetCode: Binary Tree Inorder Traversal
- [LeetCode]Binary Tree Inorder Traversal
- LeetCode Binary Tree Inorder Traversal
- [Leetcode] Binary Tree Inorder Traversal
- Leetcode: Binary Tree Inorder Traversal
- LeetCode Binary Tree Inorder Traversal
- LeetCode : Binary Tree Inorder Traversal
- [Leetcode] Binary Tree Inorder Traversal
- 【leetcode】Binary Tree Inorder Traversal
- [LeetCode]Binary Tree Inorder Traversal
- Leetcode: Binary Tree Inorder Traversal
- [leetcode]Binary Tree Inorder Traversal
- LeetCode-Binary Tree Inorder Traversal
- Leetcode Binary Tree Inorder Traversal
- [leetcode] Binary Tree Inorder Traversal
- LeetCode - Binary Tree Inorder Traversal
- [LeetCode] Binary Tree Inorder Traversal
- LeetCode | Binary Tree Inorder Traversal
- mac上的终端bash命令(二)基础
- DeviceIoControl 直接从磁盘扇区读文件
- openssl的安装
- no module named pygame
- StringBuffer内容清空效率比较
- [leetcode] Binary Tree Inorder Traversal
- List、Map和Set的实现类
- uva 1588Kickdown
- 在aws默认的linux的instance上如何迅速安装java环境
- 关于启动超时的问题
- Java之七:HashMap的实现原理
- 桑德菲杰快圣诞节
- linux_driver自动创建节点的解析
- air报错 "Context3D not available." fd as3项目默认不开启gpu加速的问题