树的遍历及复杂度分析

树的遍历及复杂度分析

时间复杂度:由于要遍历树的所有节点,故时间复杂度均为O(n)

空间复杂度:递归算法用函数栈实现,空间复杂度即为栈的深度,也即树的高度O(logn)

此时的栈中存参数,函数指针,局部变量。

前序遍历

print(TreeNode * root)

{

if(root!=NULL){

cout<<root->val<<endl;

print(root->left);

print(root->right);

}

}

posted @ 2019-12-06 14:08  柠檬味呀  阅读(4147)  评论(0)    收藏  举报