文章链接:
110
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
if(root == NULL)
return true;
if(abs(maxDepth(root->left)-maxDepth(root->right))>1)
return false;
if(isBalanced(root->left)&&isBalanced(root->right))
return true;
return false;
}
int maxDepth(TreeNode* root){
if(root == NULL)
return 0;
return max(maxDepth(root->left),maxDepth(root->right))+1;
}
};
257
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
}
LinkedList<String>path = new LinkedList<>();
LinkedList<String>res = new LinkedList<>();
void traverse(TreeNode root){
if(root == null){
return;
}
if(root.left == null && root.right == null){
path.addLast(root.val+"");
res.addLast(String.join("->",path));
path.removeLast();
return;
}
path.addLast(root.val+"");
traverse(root.left);
traverse(root.right);
path.removeLast();
}
}
404
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
* right(right) {}
* };
*/
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
traverse(root);
return sum;
}
int sum = 0;
void traverse(TreeNode* root) {
if (root == nullptr) {
return;
}
if (root->left != nullptr && root->left->left == nullptr &&
root->left->right == nullptr) {
sum += root->left->val;
}
traverse(root->left);
traverse(root->right);
}
};
222
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int cnt = 0;
int countNodes(TreeNode* root) {
TreeNode* l = root;
TreeNode* r= root;
int hl = 0,hr = 0;
while(l != nullptr){
l = l->left;
hl++;
}
while(r !=nullptr){
r = r->right;
hr++;
}
if(hl == hr){
return (int)pow(2,hl)-1;
}
return 1+ countNodes(root->left)+countNodes(root->right);
}
};