您的位置:首页 > 编程语言 > C语言/C++

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].

算法

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: