60:Binary Tree Inorder Traversal
来源:互联网 发布:java线程同步面试题 编辑:程序博客网 时间:2024/06/05 10:02
题目: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?
有三种解法,分别是递归,用栈迭代以及 Morris 前序遍历
解题代码一:
// 递归版本,时间复杂度 O(n)class Solution {public: vector<int> inorderTraversal(TreeNode* root) { vector<int> result; inorderTraversal(root, result); return result; }private: void inorderTraversal(TreeNode *root, vector<int>& result) { if (root != nullptr) { inorderTraversal(root -> left); result.push_back(root -> val); inorderTraversal(root -> right); } }};
解题代码二:
// 迭代版本,使用栈// 时间复杂度 O(n),空间复杂度 O(n)class Solution {public: vector<int> inorderTraversal(TreeNode* root) { vector<int> result; stack<const TreeNode*> s; const TreeNode* cur = root; while (!s.empty() || cur != nullptr) { if (cur != nullptr) { s.push(cur); cur = cur -> left; } else { cur = s.top(); s.pop(); result.push_back(cur -> val); cur = cur -> right; } } return result; }};
解题代码三:
// morris 遍历// 时间复杂度 O(n),空间复杂度 O(1)class Solution {public: vector<int> inorderTraversal(TreeNode* root) { vector<int> result; TreeNoede* cur = root; while (cur != nullptr) { if (cur -> left == nullptr) { result.push_back(cur -> val); cur = cur -> right; } else { TreeNode* node = cur -> left; while (node -> right != nullptr && node -> right != cur) node = node -> right; if (node -> right == nullptr) { node -> right = cur; cur = cur -> left; } else { result.push_back(cur -> val); node -> right = nullptr; cur = cur -> right; } } } return result; }};
0 0
- 60:Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- 开启博客之旅
- seleniumWebDriver的API高级应用Log4j打印执行日志11_2
- 【LeetCode】No.169 Majority Element
- Google安全视频
- [leetcode 312. Burst Ballons] hard |week 2
- 60:Binary Tree Inorder Traversal
- 解决UnicodeEncodeError: 'ascii' codec can't encode characters in position 问题
- TCP的三次握手和四次挥手
- Linux环境安装Nexus
- 不使用Cygwin,在eclipse中快速开发JNI,一键生成C头文件.h,以及一键使用NDK交叉编译
- Windows下使用Git管理本地代码
- 61:Binary Tree Postorder Traversal
- 仿QQ群组邀请功能
- In Action