【二叉树经典问题】94. Binary Tree Inorder Traversal
来源:互联网 发布:指南针软件怎么使用 编辑:程序博客网 时间:2024/05/21 06:22
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree [1,null,2,3]
,
1 \ 2 / 3
return [1,3,2]
.
Note: Recursive solution is trivial, could you do it iteratively?
一种典型的错解:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: vector<int> inorderTraversal(TreeNode* root) { vector<int> res; if(!root) return res; inorderTraversal(root->left); res.push_back(root->val); inorderTraversal(root->right); return res; }};错误的原因是,在递归调用的过程中每一次都新建了vector<int> res,调用结束就被销毁了,所以最后只能得到最后返回那一步的res,这个res只会包含根。
正解:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: vector<int> inorderTraversal(TreeNode* root) { vector<int> res; //if(!root) return res; inorder(root,res); return res; } void inorder(TreeNode* &root,vector<int>& res){ if(!root) return; inorder(root->left,res); res.push_back(root->val); inorder(root->right,res); }};
非递归:
class Solution {public: vector<int> inorderTraversal(TreeNode* root) { stack<TreeNode*> s; vector<int> res; while(root||!s.empty()){ while(root){ s.push(root); root=root->left; } root=s.top(); s.pop(); res.push_back(root->val); root=root->right; } return res; }};
阅读全文
0 0
- 【二叉树经典问题】94. Binary Tree Inorder Traversal
- 【二叉树经典问题】106. Construct Binary Tree from Inorder and Postorder Traversal
- 【二叉树经典问题】105. Construct Binary Tree from Preorder and Inorder Traversal
- 二叉树遍历94. Binary Tree Inorder Traversal
- 【二叉树经典问题】102. Binary Tree Level Order Traversal
- 【二叉树经典问题】 144. Binary Tree Preorder Traversal
- 【二叉树经典问题】145. Binary Tree Postorder Traversal
- 94.Binary Tree Inorder Traversal(二叉树先序遍历)
- [leetcode-二叉树中序遍历]--94. Binary Tree Inorder Traversal
- 二叉树中序遍历——94. Binary Tree Inorder Traversal
- leetcode 94. Binary Tree Inorder Traversal 二叉树中序递归遍历
- 94. Binary Tree Inorder Traversal
- 94.Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal
- 94.Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal
- 94. Binary Tree Inorder Traversal
- FreeRTOS_004_FreeRTOSConfig.h配置文件(一)_通用配置
- 网站系统架构梳理-解决高负载高并发
- mac hdmi 外接显示器没声音
- SQL获取年月日方法
- 兼容ie6 | SWFObject、Flash & json2以及动态JavaScript片段加载
- 【二叉树经典问题】94. Binary Tree Inorder Traversal
- HBase全网最佳学习资料汇总
- DOM操作——怎样添加、移除、移动、复制、创建和查找节点
- C#中ArrayList类的元素访问
- hdu 4059 The Boss on Mars(容斥原理)
- bzoj2243染色 树链剖分+线段树
- Redis安装
- 【如有需要找的书籍pdf版,请在这篇博客下方留言,博主及时补充】
- Java虚拟机详解----常用JVM配置参数