leetcode 刷题之路 20 Binary Tree Inorder Traversal
2014-07-27 22:57
239 查看
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree
return
Note: Recursive solution is trivial, could you do it iteratively?
二叉树的中序遍历,要求采用非递归实现。
根据中序遍历的顺序,对于任一结点,优先访问其左孩子,而左孩子结点又可以看做一个结点,然后继续访问其左孩子结点,直到遇到左孩子结点为空的结点才进行访问根节点,然后按相同的规则访问其右子树。对于任意一个节点,处理过程为:
若其左孩子不为空,则将该节点入栈并将其的左孩子置为当前的节点,然后对当前结点再进行相同的处理;
若其左孩子为空,则取栈顶元素并进行出栈操作,存储该栈顶节点,然后将当前节点置为栈顶结点的右孩子再进行相同的操作;
重复上述过程直到栈空。
测试通过代码:
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) { stack<TreeNode*> s; TreeNode *p = root; vector<int> vi; while (p != NULL || !s.empty()) { while (p != NULL) { s.push(p); p = p->left; } if (!s.empty()) { p = s.top(); s.pop(); vi.push_back(p->val); p = p->right; } } return vi; } };
相关文章推荐
- leetcode 刷题之路 64 Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode-20]Construct Binary Tree from Inorder and Postorder Traversal
- leetcode 刷题之路 64 Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode-20]Construct Binary Tree from Inorder and Postorder Traversal
- leetcode 刷题之路 74 Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode]Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode]Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode] Construct Binary Tree from Preorder and Inorder Traversal
- 【LeetCode with Python】 Binary Tree Inorder Traversal
- leetcode 63: Binary Tree Inorder Traversal
- [LeetCode] Construct Binary Tree from Preorder and Inorder Traversal
- [Leetcode] Binary Tree Inorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- [leetcode]Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode] Binary Tree Inorder Traversal - Iteratively
- LeetCode: Binary Tree Inorder Traversal
- Leetcode: Construct Binary Tree from Preorder and Inorder Traversal
- Leetcode: Binary Tree Inorder Traversal
- [leetcode]Construct Binary Tree from Preorder and Inorder Traversal
- [Leetcode] Construct Binary Tree from Preorder and Inorder Traversal