学习目标:
搜索与回溯算法
学习内容:
剑指 Offer 55 - I. 二叉树的深度
DFS
/**
* 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;
return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
};
剑指 Offer 55 - II. 平衡二叉树
/**
* 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:
bool isBalanced(TreeNode *root) {
if (root == NULL)
return true;
if (abs(maxDepth(root->left) - maxDepth(root->right)) > 1) {
return false;
}
return isBalanced(root->left) && isBalanced(root->right);
}
int maxDepth(TreeNode *root) {
if (root == NULL)
return 0;
return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
};
我好了,谢谢田田,