leetcodeBinary Tree Inorder Traversal
来源:互联网 发布:linux服务器增加硬盘 编辑:程序博客网 时间:2024/05/16 05:32
题目描述
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [1,3,2]
.
Note: Recursive solution is trivial, could you do it iteratively?
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
解题方法
中序遍历二叉树:递归方法:
class Solution {public: vector<int> inorderTraversal(TreeNode* root) { vector<int> res; if(root==NULL) return res; return inorder(res,root); } vector<int> inorder(vector<int>& res,TreeNode* root) { if(root) { inorder(res,root->left); res.push_back(root->val); inorder(res,root->right); } return res; }};
迭代方法:
仿照前序遍历使用堆栈,不过是左节点先入栈,直到左孩子为空,出栈,入栈顶元素的右孩子,然后再入右子树的左孩子节点。依次直到堆栈为空,值得注意的是,中序遍历跟先序遍历起始不同的是,根节点不最先入栈!!!代码如下:
class Solution {public: vector<int> inorderTraversal(TreeNode* root) { vector<int> res; if(root==NULL) return res; stack<TreeNode*> st; TreeNode* node=root; while(!st.empty()||node) { if(node) { st.push(node); node=node->left; } else { TreeNode* temp=st.top(); res.push_back(temp->val); st.pop(); node=temp->right; } } return res; }};
0 0
- leetcodeBinary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Ext.form.FieldSet字段集
- MySQL索引背后的数据结构及算法原理
- 分布式系统互斥算法---分布式算法
- 软件下载 itellyou
- Hbase安装过程中遇到的问题
- leetcodeBinary Tree Inorder Traversal
- [leetcode][list] Swap Nodes in Pairs
- 斐波那契的两种实现方法
- thinkphp verify验证码使用
- android.view.InflateException: Binary XML file line #7: Error inflating class
- 数据库的最简单实现
- c 语言常用基础语句
- Window下使用eclipse连接hadoop报错(二)
- nyoj题目277:车牌号