Leetcode在线编程 binary-tree-inorder-traversal
2017-01-05 20:21
656 查看
Leetcode在线编程 binary-tree-inorder-traversal
题目链接
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?
题意
给定二叉树,求非递归的中序遍历解题思路
首先考虑中序遍历的一个实质,便是先访问左子树,再访问根节点,最后访问右子树分为以下3种情况
有左子树并且左子树还没被访问,那么此节点还不能遍历
有左子树,且左子树已经被访问,那么该节点就可以遍历
没有左子树,则直接可以遍历
每个节点都一直遍历左儿子,并压入栈,直到该节点为空
此时栈顶的节点一定是没有左儿子或者左儿子已经被访问了,那么一定可以被遍历,则把该节点出栈,并将其右孩子设为下一个要入栈的节点,重复以上操作,一直到栈为空为止。
AC代码
class Solution { public: vector<int> inorderTraversal(TreeNode *root) { vector<int> v; if(root ==NULL) return v; stack<TreeNode*>s; while(root!=NULL||!s.empty()) { while(root!=NULL) { s.push(root); root = root->left; } if(!s.empty()) { TreeNode *tmp = s.top(); v.push_back(tmp->val); s.pop(); if(tmp->right!=NULL) root = tmp->right; } } return v; } };
相关文章推荐
- leetcode在线编程binary-tree-postorder-traversal
- leetcode--construct_binary_tree_from_preorder_and_inorder_traversal
- Leetcode在线编程minimum-depth-of-binary-tree
- *Leetcode_construct-binary-tree-from-inorder-and-postorder-traversal
- leetcode — construct-binary-tree-from-preorder-and-inorder-traversal
- leetcode编程记录8 #107 Binary Tree Level Order Traversal II
- *Leetcode_construct-binary-tree-from-preorder-and-inorder-traversal
- LeetCode--construct-binary-tree-from-preorder-and-inorder-traversal
- leetcode--ConstructBinaryTreefromInorderandPostorderTraversal
- 4.35 leetcode -35 binary-tree-inorder-traversal
- LeetCode--construct-binary-tree-from-inorder-and-postorder-traversal
- LeetCode--binary-tree-inorder-traversal
- Leetcode-binary-tree-inorder-traversal
- Leetcode_binary-tree-inorder-traversal
- leetcode — binary-tree-inorder-traversal
- leetcode — construct-binary-tree-from-inorder-and-postorder-traversal
- leetcode--ConstructBinaryTreefromInorderandPostorderTraversal
- leetcode — construct-binary-tree-from-preorder-and-inorder-traversal
- leetcode — binary-tree-inorder-traversal
- leetcode — construct-binary-tree-from-inorder-and-postorder-traversal