Leetcode 剑指系列 Day 18 搜索与回溯
1.剑指 Offer 55 - I. 二叉树的深度
解题思路:
先序遍历树即可
class Solution {
public:
int findDepth(TreeNode* Node, int depth){
if(Node == NULL) return depth;
depth++;
return max(findDepth(Node->left, depth), findDepth(Node->right, depth));
}
int maxDepth(TreeNode* root) {
int depth = 0;
return findDepth(root, depth);
}
};
2.剑指 Offer 55 - II. 平衡二叉树
解题思路:
后序遍历避免重复计算
class Solution {
public:
int pOrderForDepth(TreeNode* node, int depth){
if(node == NULL) return depth;
int depth1 = pOrderForDepth(node->left, depth);
int depth2 = pOrderForDepth(node->right, depth);
if(depth1 - depth2 > 1 || depth2 - depth1 > 1) return -1;
if(depth1 >= 0 && depth2 >= 0) return max(depth1, depth2) + 1;
else return -1;
}
bool isBalanced(TreeNode* root) {
int ans = pOrderForDepth(root, 0);
if(ans >= 0) return true;
else return false;
}
};