Binary Tree Inorder Traversal [leetcode] 非递归的三种解法
2014-09-27 20:46
471 查看
第一种方法是Morris Traversal
是O(n)时间复杂度,且不需要额外空间的方法。缺点是需要修改树。
通过将叶子节点的right指向其中序后继。
代码如下
第二种方法利用栈,模拟递归过程
第三种方法来自《数据结构》
将所有左子节点入栈,当没有左子结点时取栈顶元素打印并转移到右子节点
是O(n)时间复杂度,且不需要额外空间的方法。缺点是需要修改树。
通过将叶子节点的right指向其中序后继。
代码如下
vector<int> inorderTraversal(TreeNode *root) { vector<int> res; TreeNode * cur = root; TreeNode * pre = NULL; while (cur) { if (cur->left == NULL) { res.push_back(cur->val); cur = cur->right; } else { pre = cur->left; while (pre->right && pre->right != cur) pre = pre->right; if (pre->right == NULL) { pre->right = cur; cur = cur->left; } if (pre->right == cur) { pre->right = NULL; res.push_back(cur->val); cur = cur->right; } } } return res; }
第二种方法利用栈,模拟递归过程
vector<int> inorderTraversal(TreeNode *root) { vector<int> res; vector<TreeNode*> stack; stack.push_back(root); set<TreeNode*> visited; while (stack.size()) { TreeNode * cur = stack.back(); stack.pop_back(); if (!cur) continue; if (visited.find(cur) == visited.end())//visited for the first time { stack.push_back(cur->right); stack.push_back(cur); stack.push_back(cur->left); visited.insert(cur); } else//visited for the second time res.push_back(cur->val); } return res; }
第三种方法来自《数据结构》
将所有左子节点入栈,当没有左子结点时取栈顶元素打印并转移到右子节点
vector<int> inorderTraversal(TreeNode *root) { vector<int> res; vector<TreeNode*> stack; TreeNode* cur = root; while (stack.size() || cur) { if (cur) { stack.push_back(cur); cur = cur->left; } else { cur = stack.back(); stack.pop_back(); res.push_back(cur->val); cur = cur->right; } } return res; }
相关文章推荐
- [leetCode]Binary Tree Inorder Traversal 递归 && 栈解法
- [Leetcode]Binary Tree Inorder Traversal@python(附前、中、后三种遍历的递归和非递归方法!)
- LeetCode Binary Tree Postorder Traversal 二叉树后序遍历 递归和非递归解法
- leetcode_94题——Binary Tree Inorder Traversal (二叉树,递归,队列queue,栈stack,set)
- [LeetCode] Binary Tree Inorder Traversal [递归版]
- leetcode_105题——Construct Binary Tree from Preorder and Inorder Traversal(树,递归)
- LeetCode Binary Tree Preorder Traversal 前序遍历二叉树 递归和非递归解法
- Leetcode 94:Binary Tree Inorder Traversal (二叉树中序遍历,非递归)
- 【LeetCode】Binary Tree Inorder Traversal 二叉树中序遍历递归以及非递归算法
- LeetCode-Construct Binary Tree from Preorder and Inorder Traversal-前序中序恢复二叉树-递归
- LeetCode-Construct Binary Tree from Inorder and Postorder Traversal-中序后序重构二叉树-递归
- LeetCode Binary Tree Inorder Traversal
- LeetCode: Binary Tree Inorder Traversal
- [LeetCode] Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode] Construct Binary Tree from Preorder and Inorder Traversal
- leetcode 63: Binary Tree Inorder Traversal
- [LeetCode] Construct Binary Tree from Preorder and Inorder Traversal, Solution
- [leetcode]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