树和二叉树
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了树和二叉树相关的知识,希望对你有一定的参考价值。
二叉树的定义如下:树要么为空,要么由根结点、左子树、右子树组成,而左子树和右子树分别是一颗二叉树。注意,在计算机中,树一般是“倒置”的,即根在上,叶子在下。
而树的定义比二叉树区别在于有很多的子树。
但是不管是二叉树还是树,每个非根结点都有一个父节点。
简单的二叉树实现代码(C++)
struct Tree { int data; struct Tree *left; struct Tree *right; };
二叉树深度的求法可以用简单的递归就可以实现
int maxDepth(Tree *root) { if(!root) return 0; int leftDepth = maxDepth(root -> left) + 1; int rightDepth = maxDepth(root -> right) + 1; return leftDepth >= rightDepth?leftDepth:rightDepth; }
二叉树的三种遍历方式:
前序、中序、后序
前序遍历:根节点->左子树->右子树
中序遍历:左子树->根节点->右子树
后序遍历:左子树->右子树->根节点
递归实现如下
void preorder_print(Tree *tree) { if(tree){ std::cout << tree -> data; preorder_dev(tree -> left); preorder_dev(tree -> right); } } void inorder_print(Tree * tree) { if(tree) { print_inorder(tree->left); std::cout << tree -> data; print_inorder(tree->right); } } void postorder_print(Tree * tree) { if(tree) { print_postorder(tree->left); print_postorder(tree->right); std::cout << tree -> data; } }
非递归,栈的方法实现
void preorder_stack(Tree *tree){ std::stack<Tree> stack; Tree *p = tree; while (p || !stack.empty()) { if(p != NULL) { stack.push(*p); printf("%d ",p->data); p = p -> left; } else { p = &stack.top(); stack.pop(); p = p -> right; } } } void inorder_stack(Tree *tree){ std::stack<Tree> stack; Tree *p = tree; while(p || !stack.empty()){ if(p != NULL){ stack.push(*p); p = p -> left; } else { p = &stack.top(); printf("%d ",p -> data); stack.pop(); p = p -> right; } } } //后续遍历需要标示是否已经达到根结点,1为左 2为右 struct PostTree { Tree *tree; int IsChecked = 0; }; typedef PostTree PostTree; void postorder_stack(Tree *tree){ std::stack<PostTree> stack; Tree *p = tree; PostTree *post; while (p || !stack.empty()) { //遍历左节点 while(p != NULL){ post = (PostTree *)malloc(sizeof(PostTree)); post ->tree = p; post ->IsChecked = 1; stack.push(*post); p = p -> left; } //遍历右结点 while(!stack.empty()){ post = &stack.top(); post -> IsChecked = 2; p = post->tree; p = p -> right; } //访问根结点 while (!stack.empty() && (stack.top()).IsChecked == 2) { post = &stack.top(); stack.pop(); printf("%d ",post -> tree -> data); } }//end while }
以上是关于树和二叉树的主要内容,如果未能解决你的问题,请参考以下文章