OJ链接:https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof/submissions/
当前树的深度 = max(左子树深度,右子树深度)+1,所以要求当前树的深度得先递归求出左子树深度和右子树深度。要求出左右子树的深度同样的道理,再往下递归,直到遇到空树,深度直接返回0。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == NULL)
return 0;
int leftDepth = maxDepth(root->left);
int rightDepth = maxDepth(root->right);
return leftDepth > rightDepth ? leftDepth+1 : rightDepth+1;
}
};
OJ链接:https://leetcode-cn.com/problems/balanced-binary-tree/
什么是高度平衡二叉树?一颗二叉树的左右子树的高度差不超过1,且树中的所有子树都满足这个条件,则称这颗二叉树是高度平衡二叉树。
那么要判断一颗二叉树是否是平衡二叉树可以分为3步:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == NULL)
return 0;
int leftDepth = maxDepth(root->left);
int rightDepth = maxDepth(root->right);
return leftDepth > rightDepth ? leftDepth+1 : rightDepth+1;
}
bool isBalanced(TreeNode* root) {
if(root == NULL)
return true;
int leftDepth = maxDepth(root->left);
int rightDepth = maxDepth(root->right);
return abs(leftDepth-rightDepth) < 2
&& isBalanced(root->left)
&& isBalanced(root->right);
}
};
OJ链接:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* _buildTree(vector& preorder, vector& inorder, int& prei, int inbegin, int inend)
{
if(inbegin > inend) return nullptr;
int rootVal = preorder[prei];
TreeNode* root = new TreeNode(rootVal);
// 在中序序列中去找root的位置
int inRooti = inbegin;
while(inRooti <= inend)
{
if(inorder[inRooti] == rootVal)
break;
else
++inRooti;
}
// [inbegin, inRooti-1] inRooti [inRooti+1, inend] 左子树的中序[inbegin, inRooti-1] 右子树的中序[inRooti+1, inend]
// 如果中序左区间存在则递归创建左子树,如果中序左区间不存在,则左子树是空树
if(inbegin <= inRooti-1)
root->left = _buildTree(preorder, inorder, ++prei, inbegin, inRooti-1);
else
root->left= nullptr;
// 同上
if(inRooti+1 <= inend)
root->right = _buildTree(preorder, inorder, ++prei, inRooti+1, inend);
else
root->right = nullptr;
return root;
}
TreeNode* buildTree(vector& preorder, vector& inorder)
{
int prei = 0;
int inbegin = 0;
int inend = inorder.size()-1;
return _buildTree(preorder, inorder, prei, inbegin, inend);
}
};
如果你有不是很明白的地方,这里有讲解视频哦:
数据结构高频面试题之二叉树(上)(C++实现)
或者点击链接观看:单击链接就可以了
数据结构面试题及答案解析系列如果对你有帮助,请点赞,转发,鼓励博主继续更新下去哦
上一篇:https://blog.csdn.net/bitzhidu/article/details/106474004
下一篇:https://blog.csdn.net/bitzhidu/article/details/106626412