第一次在leetcode上做树的题目,有点眼花缭乱了。浅抄一下。
94.二叉树的中序遍历
class Solution {
public:
void inorder(TreeNode* root, vector<int>& res) {
if (!root) {
return;
}
inorder(root->left, res);
res.push_back(root->val);
inorder(root->right, res);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
inorder(root, res);
return res;
}
};
101对称二叉树
class Solution {
public:
void inorder(TreeNode* root, vector<int>& res) {
if (!root) {
return;
}
inorder(root->left, res);
res.push_back(root->val);
inorder(root->right, res);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
inorder(root, res);
return res;
}
};
class Solution {
public:
bool isBalanced(TreeNode* root) {
if(root==NULL) return true;
else return abs(count(root->left)-count(root->right))<=1&&isBalanced(root->left)&&isBalanced(root->right);
}
int count(TreeNode *T){
if(T==NULL) return 0;
else{
int l=count(T->left);
int r=count(T->right);
return l>r?l+1:r+1;
}
}
};
最近感觉做一些leetcode也很不错,以前为什么那么抗拒代码。。。。