class Solution {
public:
int getHigh(TreeNode* node){
if(node == NULL) return 0;
int left = getHigh(node->left);
if (left==-1) return -1;
int right = getHigh(node->right);
if (right==-1) return -1;
int result;
if(abs(left - right) > 1){
return -1;
}else{
return 1 + max(left,right);
}
}
bool isBalanced(TreeNode* root) {
return getHigh(root) == -1 ? false : true;
}
};
感觉写了好多的递归之后还是不是很熟练,基本都是后序左右中,主要是内部逻辑这一块有时候想不到,如果高度差大于1,就返回-1,否则返回1+最大高度差;
递归回溯法:
class Solution {
public:
void traversal(TreeNode* node,string path,vector<string>& result){
path += to_string(node->val);
if(node->left==NULL&&node->right==NULL){
result.push_back(path);
return;
}
if(node->left) traversal(node->left,path+"->",result);
if(node->right) traversal(node->right,path+"->",result);
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
string path;
if(root==NULL) return result;
traversal(root,path,result);
return result;
}
};
path中存储的是根节点到当前结点的路径表示;
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if(root == NULL) return 0;
if(root->left==NULL&&root->right==NULL){
return 0;
}
int left = sumOfLeftLeaves(root->left);
int sum = 0;
if(root->left!=NULL&&root->left->left==NULL&&root->left->right==NULL){
left = root->left->val;
}
int right = sumOfLeftLeaves(root->right);
sum = left + right;
return sum;
}
};
还是递归后序遍历的思想,当遇到左结点时让left为左结点值;注意通过父节点判断是否为左叶子;