树的遍历
前序遍历
-
首先访问根节点,然后遍历左子树,最后遍历右子树
递归写法
void preTravel(struct TreeNode*root)
{
if(root!=NULL)
{
printf("%d",root->val);
travel(root->left);
travel(root->right);
}
}迭代写法 (迭代就是把递归过程中调用的栈显式表达出来)
void preTravel(struct TreeNode*root)
{
struct TreeNode *stk[100];
int stk_top = -1;
while (stk_top > -1 || root != NULL)
{
while (root != NULL)
{
printf("%d",root->val);
stk[++stk_top] = root;
root = root->left;
}
root = stk[stk_top--];
root = root->right;
}
}
中序遍历
-
先左后根最后右(==二叉搜索树中可以得到递增的有序序列==)
递归写法
void inorderTravel(struct TreeNode*root)
{
if(root==NULL)
return;
inorderTravel(root->left);
printf("%d",root->val);
inorderTravel(root->right);
}迭代写法 (迭代就是把递归过程中调用的栈显式表达出来)
void inorderTravel(struct TreeNode*root)
{
struct TreeNode *stk[100];
int stk_top = -1;
while (stk_top > -1 || root != NULL)
{
while (root != NULL)
{
stk[++stk_top] = root;
root = root->left;
}
root = stk[stk_top--];
printf("%d",root->val);
root = root->right;
}
}
后序遍历
-
先左后右最后根
递归写法
void postTravel(struct TreeNode*root)
{
if(root==NULL)
return;
postTravel(root->left,a,returnSize);
printf("%d",root->val);
postTravel(root->right,a,returnSize);
}迭代写法
void preTravel(struct TreeNode*root)
{
struct TreeNode *stk[100];
struct TreeNode *prev = NULL;
int stk_top = -1;
if(root==NULL)
return;
while (stk_top > -1 || root != NULL)
{
while (root != NULL)
{
stk[++stk_top] = root;
root = root->left;
}
root=stk[stk_top--];
if (root->right == NULL || root->right == prev) {
printf("%d",root->val);
prev = root;
root = NULL;
}
else
{
stk[top++] = root;
root = root->right;
}
}
}
层序遍历
- 用队列实现广度优先搜索,逐层遍历
|
递归解决问题
- 最大深度
int maxDepth(struct TreeNode* root){ |
- 对称二叉树
bool isMirror(struct TreeNode*p,struct TreeNode*q) |
- 路径总和
//判断二叉树中是否有一条路径节点之和等于目标值 |
- 最近公共祖先
struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) { |
- 最长路径
|