二叉树的高其实很简单就一句话:
从根节点到叶节点的最长路径中的边数就是二叉树的高
int FindHeight(Btree root){int leftheight;int rightheight;if(root==NULL){return -1;}else{leftheight=FindHeight(root->left );rightheight=FindHeight(root->right );}return (max(leftheight,rightheight))+1;}
二叉树的遍历深度优先和广度优先
广度优先遍历 就是一层一层的遍历,也叫做层序遍历
深度优先可以分为三种,前序,中序,后序 遍历
前序遍历
访问根节点;② 先序遍历左子树;③ 先序遍历右子树。(简记为 “根左右”)
上图的前序遍历顺序为:F,D,B,A,C,E,J,G,I,H,K
中序遍历
若二叉树为空,则什么也不做;否则:
① 中序遍历左子树;② 访问根节点;③ 中序遍历右子树。(简记为 “左根右”)
上图的中序遍历顺序为:A,B,C,D,E,F,G,H,I,J,K
后序遍历
若二叉树为空,则什么也不做;否则:
① 后序遍历左子树;② 后序遍历右子树;③ 访问根节点;(简记为 “左右根”)
后序遍历的顺序为
A.C,B,E,D,H,I,G,K,J,F
OK,搞清楚这些之后,我们来写一下代码。首先我们来写一下层序遍历的代码
层序遍历我们需要借助队列来写,如下图,一个元素出对,他的左右节点就要入队这就是层序遍历的精华,直到队列为空,我们的层序遍历也就结束啦
前序遍历
这两张
图太重要了
代码如下
void LevelOrder(Btree root){if(root==NULL)return ;else{queue<node*> Q;Q.push(root);while(!Q.empty()){Btree current=Q.front();cout<<current->data<<" ";if(current->left!=NULL)Q.push(current->left);if(current->right!=NULL)Q.push(current->right);Q.pop();//remove at front}}}void preorder(Btree root){if(root==NULL) return;else{cout<<root->data<<" ";preorder(root->left );preorder(root->right );}}void Inorder(Btree root){if(root==NULL)return;else{Inorder(root->left);cout<<root->data<<" ";Inorder(root->right);}}
void postorder(Btree root)
{if(root==NULL)return;else{postorder(root->left);postorder(root->right );cout<<root->data<<" ";}}
判断是否是二叉树,运用了很强的递归逻辑,认真思考一下
bool IsSubtreeLesser(Btree root,int value)
{if(root==NULL) return true;if(root->data<=value&&IsSubtreeLesser(root->left,value)&&IsSubtreeLesser(root->right,value))return true;elsereturn false;
}
bool IsSubtreeGreater(Btree root,int value)
{if(root==NULL) return true;if(root->data > value && IsSubtreeGreater(root->left,value)&&IsSubtreeGreater(root->right,value))return true;elsereturn false;}
bool IsBinarySearchTree(Btree root)
{//return true if bstif(IsSubtreeLesser(root->left,root->data)&&IsSubtreeGreater(root->right,root->data )&&IsBinarySearchTree(root->left )&&IsBinarySearchTree(root->right))return true;
}