leetcode_c++:哈希:Binary Tree Inorder Traversal(094)
2016-07-02 14:51
543 查看
Given a binary tree, return the inorder traversal of its nodes’ values.
For example:
Given binary tree [1,null,2,3],
1
\
2
/
3
return [1,3,2].
递归方法
当二叉树高度为N时,此时递归层序遍历为最坏情况,时间复杂度为O(N^2)。当二叉树左右子树基本平衡时,时间复杂度为O(N),分析如下:
设访问第K层时间为T(k),则T(k)存在如下的递归公式:
T(k) = 2T(k-1) + c
= 2k-1 T(1) + c
= 2k-1 + c
当二叉树平衡时,则高度为O(lgN),则总时间为:
T(1) + T(2) + … + T(lg N)
= 1 + 2 + 22 + … + 2lg N-1 + c
= O(N)
非递归解法
空间复杂度O(N)
For example:
Given binary tree [1,null,2,3],
1
\
2
/
3
return [1,3,2].
算法
O(n)递归方法
当二叉树高度为N时,此时递归层序遍历为最坏情况,时间复杂度为O(N^2)。当二叉树左右子树基本平衡时,时间复杂度为O(N),分析如下:
设访问第K层时间为T(k),则T(k)存在如下的递归公式:
T(k) = 2T(k-1) + c
= 2k-1 T(1) + c
= 2k-1 + c
当二叉树平衡时,则高度为O(lgN),则总时间为:
T(1) + T(2) + … + T(lg N)
= 1 + 2 + 22 + … + 2lg N-1 + c
= O(N)
// // main.cpp // CplusplusTest // // Created by mijian on 16/7/1. // Copyright © 2016年 mijian. All rights reserved. // #include <iostream> #include <string> #include <vector> #include <map> #include<limits.h> #include <unordered_map> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { private: void orderhelper(vector<int> &res,TreeNode *cur){ if(!cur) return; if(cur->left) orderhelper(res,cur->left); res.push_back(cur->val); if(cur->right) orderhelper(res,cur->right); } public: vector<int> inorderTraversal(TreeNode* root) { vector<int> res; orderhelper(res,root); return res; } };
算法
o(N)非递归解法
空间复杂度O(N)
class Solution { public: vector<int> inorderTraversal(TreeNode *root) { vector<int> path; stack<TreeNode *> st; if (root == NULL) return path; TreeNode *p = root; while (p != NULL || !st.empty()) { while (p != NULL) { st.push(p); p = p->left; } if (!st.empty()) { p = st.top(); st.pop(); path.push_back(p->val); p = p->right; } } return path; } };
相关文章推荐
- leetcode_c++:哈希:Group Anagrams (076)
- (c++)——内联函数
- 提高项目19-有序数组中插入数据
- c#中的委托和c++中的bind/function对比
- 提高项目18-二分法解方程
- leetcode_c++:哈希:Group Anagrams (049)
- 提高项目17-有几个
- C语言实现六种排序算法
- 提高项目16.2 村民奖金2
- 函数
- IEEE POSIX 标准
- C++ 类的多态二(函数重载--函数重写--函数重定义)
- ISO C 标准
- union内存分配
- HDU1421 搬寝室(DP)
- 二叉查找树(二)之 C++的实现
- 二叉查找树(一)之 C语言的实现
- AVL树(二)之 C++的实现
- AVL树(一)之 C语言的实现
- 红黑树(三)之 C++的实现