二叉树的天然递归结构
二叉树递归查找元素
二叉树递归释放空间
复习二叉树相关的所有操作
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x): val(x), left(NULL),right(NULL) {}
};
//采用DFS的思想
int maxDepth(TreeNode *root)
{
if (NULL == root)
return 0;
int l = maxDepth(root->left);
int r = maxDepth(root->right);
return l > r ? l + 1:r+1;
//以上这两种方式有一种更简便的方法
//return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
//采用BFS的方法,引入队列
int maxDepth(TreeNode *root)
{
if (NULL == root)
return 0;
queue <TreeNode *> que;
int nCount = 1;
int nDepth = 0;// 记录队列里面每一层上的元素
que.push(root);
while(!que.empty()) {
TreeNode *pTemp = que.front();
que.pop();
nCount --;
if (pTemp->left)
que.push(pTemp->left);
if (pTemp->right)
que.push(pTemp->right);
if (nCount == 0) {
nDepth ++;
nCount = que.size();
}
}
return nDepth;
}
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x): val(x),left(NULL), right(NULL) {}
};
int minDepth(TreeNode *root)
{
if (NULL == root)
return 0;
int l = minDepth(root->left);
int r = minDepth(root->right);
if (!l)
return r+1;
if (!r)
return l+1;
return (l<r)?l+1:r+1;
}
注意递归的终止条件
更复杂的递归逻辑
二分搜索树中的问题
复习二分搜索树的基本操作:插入、查找、删除、最大值、最小值、前驱、后继、上界、下界、rank、第K大、第K小元素
红黑树了解一下