Binary Tree Inorder Traversal 二叉树的中序遍历
2015-04-24 21:24
363 查看
Binary Tree Inorder Traversal
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?
/** * 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<int> inorderTraversal(TreeNode *root) { vector<int> res; solve(root,res); return res; } void solve(TreeNode *root,vector<int> &res) { if(root!=NULL) { solve(root->left,res); res.push_back(root->val); solve(root->right,res); } } */ vector<int> inorderTraversal(TreeNode *root) { vector<int> res; stack<TreeNode* > s; TreeNode* current=root; while(!s.empty()||current!=NULL) { if(current!=NULL) { s.push(current);// 根先进,在继续左孩子,直到为空 current=current->left; } else { current=s.top(); s.pop(); res.push_back(current->val);// 根 current=current->right;//右 } } return res; } };
相关文章推荐
- [leetcode]Construct Binary Tree from Inorder and Postorder Traversal (利用中序遍历和后续遍历确定一颗二叉树)
- LintCode Binary Tree Inorder Traversal 二叉树的中序遍历(非递归)
- LeetCode | Binary Tree Inorder Traversal(二叉树的中序遍历)
- lintcode 容易题:Binary Tree Inorder Traversal 二叉树的中序遍历
- LeetCode 94 Binary Tree Inorder Traversal(二叉树的中序遍历)+(二叉树、迭代)
- 二叉树的中序遍历 Binary Tree Inorder Traversal
- LeetCode Binary Tree Inorder Traversal 中序遍历二叉树
- LeetCode 94 Binary Tree Inorder Traversal (中序遍历二叉树)
- [leetcode]Construct Binary Tree from Preorder and Inorder Traversal(根据前序、中序遍历确定一棵二叉树 C语言)
- LeetCode-94-Binary Tree Inorder Traversal 中序遍历二叉树
- LeetCode—***Binary Tree Inorder Traversal二叉树的中序遍历
- Binary Tree Inorder Traversal——二叉树的中序遍历
- Binary Tree Inorder Traversal-非递归实现中序遍历二叉树
- Binary Tree Inorder Traversal 二叉树的中序遍历(C++:Iterative solution using stack)
- [LeetCode] Binary Tree Inorder Traversal 二叉树的中序遍历
- LeetCode OJ:Binary Tree Inorder Traversal(中序遍历二叉树)
- LeetCode OJ 之 Binary Tree Inorder Traversal (二叉树的中序遍历)
- LeetCode(Construct Binary Tree from Preorder and Inorder Traversal )根据二叉树的中序遍历和后序遍历重建二叉树
- LeetCode OJ:Construct Binary Tree from Preorder and Inorder Traversal(从前序以及中序遍历结果中构造二叉树)
- Leetcode - Tree - 106. Construct Binary Tree from Inorder and Postorder Traversal(根据中序遍历和后序遍历重构二叉树)