二叉树的中序遍历 Binary Tree Inorder Traversal
2014-02-17 14:34
507 查看
方法:二叉树的先序遍历形式有递归和非递归两种。
递归方式的实现:
递归和栈总是对应的。二叉树的非递归中序遍历思想是,先让根结点进栈。然后把其左分支都进栈,直到左分支为空时才出栈,并让栈顶的右孩子入栈。
为二叉树的中序遍历操作设计一个迭代器
这样可以很方便的通过调用迭代器的接口来实现对二叉树结点的逐个遍历操作。
使用这个迭代器
先要有个二叉树:Node *p = root;
定义并初始化迭代器:InorderIterator it(p);
之后就可以使用它去遍历了,每调用一次next接口就返回下一个结点的地址:p = it->next(); (第一次调用next会返回中序遍历的第一个结点)
递归方式的实现:
class Solution { public: vector<int> inorderTraversal(TreeNode *root) { vector<int> out; fun(root, out); return out; } void fun(TreeNode *root, vector<int> &out) { if(root != NULL) { fun(root->left, out); out.push_back(root->val); fun(root->right, out); } } };非递归方式的实现:
递归和栈总是对应的。二叉树的非递归中序遍历思想是,先让根结点进栈。然后把其左分支都进栈,直到左分支为空时才出栈,并让栈顶的右孩子入栈。
class Solution { public: stack<TreeNode *> s; vector<int> inorderTraversal(TreeNode *root) { vector<int> out; TreeNode *p = root; if(root==NULL) return out; do { while(p!=NULL) { s.push(p); p = p->left; } p = s.top(); s.pop(); out.push_back(p->val); p = p->right; if(p!=NULL) { s.push(p); p = p->left; } }while(!s.empty()); return out; } };
为二叉树的中序遍历操作设计一个迭代器
这样可以很方便的通过调用迭代器的接口来实现对二叉树结点的逐个遍历操作。
//设计一个虚基类,里面的这个next是纯虚函数。 class iterator{ public: virtual Node* next() = 0; }; //中序遍历迭代器类继承一下虚基类 class InorderIterator :public iterator { public: InorderIterator(Node* node) //构造函数 { Node *p = node; while(p != NULL) { s.push(p); p = p->left; } } virtual Node* next() //迭代器接口 { if(s.empty()) return NULL; Node *cur = s.top(); s.pop(); if(cur->right != NULL) { Node*p = cur->right; while(p != NULL) { s.push(p); p = p->left; } } return cur; } private: std::stack<Node *> s; };
使用这个迭代器
先要有个二叉树:Node *p = root;
定义并初始化迭代器:InorderIterator it(p);
之后就可以使用它去遍历了,每调用一次next接口就返回下一个结点的地址:p = it->next(); (第一次调用next会返回中序遍历的第一个结点)
相关文章推荐
- [leetcode]Construct Binary Tree from Preorder and Inorder Traversal(根据前序、中序遍历确定一棵二叉树 C语言)
- Binary Tree Inorder Traversal 二叉树的中序遍历
- LeetCode 94 Binary Tree Inorder Traversal(二叉树的中序遍历)+(二叉树、迭代)
- LeetCode 94 Binary Tree Inorder Traversal (中序遍历二叉树)
- LeetCode—***Binary Tree Inorder Traversal二叉树的中序遍历
- LeetCode Binary Tree Inorder Traversal 中序遍历二叉树
- Binary Tree Inorder Traversal——二叉树的中序遍历
- Binary Tree Inorder Traversal-非递归实现中序遍历二叉树
- [LeetCode] Binary Tree Inorder Traversal 二叉树的中序遍历
- LeetCode OJ:Binary Tree Inorder Traversal(中序遍历二叉树)
- LeetCode-94-Binary Tree Inorder Traversal 中序遍历二叉树
- LeetCode(Construct Binary Tree from Preorder and Inorder Traversal )根据二叉树的中序遍历和后序遍历重建二叉树
- LeetCode OJ 之 Binary Tree Inorder Traversal (二叉树的中序遍历)
- 【遍历二叉树】02二叉树的中序遍历【Binary Tree Inorder Traversal】
- [线索二叉树] [LeetCode] 不需要栈或者别的辅助空间,完成二叉树的中序遍历。题:Recover Binary Search Tree,Binary Tree Inorder Traversal
- LeetCode OJ:Construct Binary Tree from Preorder and Inorder Traversal(从前序以及中序遍历结果中构造二叉树)
- leetcode 题解:Binary Tree Inorder Traversal (二叉树的中序遍历)
- Leetcode - Tree - 106. Construct Binary Tree from Inorder and Postorder Traversal(根据中序遍历和后序遍历重构二叉树)
- Binary Tree Inorder Traversal 二叉树的中序遍历
- Binary Tree Inorder Traversal 二叉树的中序遍历(C++:Iterative solution using stack)