视频链接:
求二叉树深度的两种方法
自底向上:
代码:
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root==nullptr)
return 0;
int depLeft = maxDepth(root->left);
int depRight = maxDepth(root->right);
return max(depLeft, depRight)+1;
}
};
自顶向下
思路:
代码:
class Solution {
public:
int result = 0;
void FindPath(TreeNode* root, int cnt){
if(root==nullptr){
result = max(cnt, result);
return;
}
cnt++;
FindPath(root->left, cnt);
FindPath(root->right, cnt);
return;
}
int maxDepth(TreeNode* root) {
FindPath(root, 0);
return result;
}
};
启发:
这里我们的递归函数void FindPath(TreeNode* root, int cnt)有一个形参,用于记录每一层的深度。
同时有一个全局变量result记录结果。
100. 相同的树
示例:
思路:
比较对应节点是否相同,不同返回false,相同则比较对应的左右子树是否相同。
代码:
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
//先判断不同
if(p==nullptr || q==nullptr){
if(p==q)
return true;
return false;
}
return p->val==q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
};
启发:
这里我们的递归函数isSameTree(TreeNode* p, TreeNode* q)传入了两个节点。
101. 对称二叉树
示例:
跟上一道题一样,但是是判断左右子树是否轴对称。
代码:
class Solution {
public:
bool isSame(TreeNode* p, TreeNode* q){
if(p==nullptr || q==nullptr){
if(p==q)
return true;
return false;
}
return p->val==q->val && isSame(p->left, q->right) && isSame(p->right, q->left);
}
bool isSymmetric(TreeNode* root) {
return isSame(root->left, root->right);
}
};
110. 平衡二叉树
示例:
思路:自底向上的想法,一步步向上递归深度。如果左右子树深度相差不超过1,则是平衡二叉树,返回深度, 否则向上返回-1。
代码:
class Solution {
public:
int CalDepth(TreeNode* root){
if(root==nullptr)
return 0;
int left = CalDepth(root->left);
int right = CalDepth(root->right);
if(left ==-1 || right==-1) return -1;
if(abs(left - right) > 1) return -1;
return max(left, right)+1;
}
bool isBalanced(TreeNode* root) {
if(CalDepth(root)!=-1) return true;
return false;
}
};
启发:
这道题设计的递归函数的返回值是深度,但是如果子树不是平衡二叉树,那么可以向上返回-1,返回值可以灵活。
199. 二叉树的右视图
示例:
思路:按照二叉树的 右 —>左 遍历顺序,整个二叉树的遍历顺序如下:
再根据 深度==结果集的长度 来判断,该元素是否需要加入结果集
代码:
class Solution {
public:
vector<int> result;
void GetAnswer(TreeNode* root, int Depth){
if(root==nullptr) return;
if(result.size()==Depth){
result.push_back(root->val);
}
Depth++;
GetAnswer(root->right, Depth);
GetAnswer(root->left, Depth);
}
vector<int> rightSideView(TreeNode* root) {
GetAnswer(root, 0);
return result;
}
};