1.平衡二叉树 leetcode
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1
class Solution {
public:
int getheight ( TreeNode* cur ) {
if ( cur == NULL ) return 0;
int leftnum = getheight ( cur -> left );
if ( leftnum == -1 ) return -1;
int rightnum = getheight ( cur -> right );
if ( rightnum == -1 ) return -1;
int result;
if ( abs(leftnum - rightnum) > 1 )result = -1 ;
else result = max(leftnum , rightnum) + 1;
return result;
}
bool isBalanced(TreeNode* root) {
int x = getheight(root);
return x == -1 ? false : true;
}
};
以 -1 作为 结束标志 ,一遇到 -1 就返回 -1 直到 最后
2.二叉树的所有路径 乐儿他从的
class Solution {
public:
void trave(TreeNode * cur , vector < int >& path , vector < string > &result ) {
path.push_back( cur -> val );
if ( cur -> right == NULL && cur -> left == NULL ) {
string a;
for ( int i = 0 ; i < path.size() - 1 ; i++ ) {
a += to_string( path[i] );
a += "->";
}
a += to_string(path[path.size() - 1]);
result.push_back(a);
}
if ( cur -> left ) {
trave( cur -> left , path , result );
path.pop_back();
}
if ( cur -> right ) {
trave( cur -> right , path , result );
path.pop_back();
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector < string > result;
vector < int > path;
trave ( root, path, result );
return result;
}
};
将 回溯过程 表现了出来 , 当遍历到叶子时 将 path 处理
也可以采取不表现回溯
class Solution {
private:
void traversal(TreeNode* cur, string path, vector<string>& result) {
path += to_string(cur->val); // 中
if (cur->left == NULL && cur->right == NULL) {
result.push_back(path);
return;
}
if (cur->left) traversal(cur->left, path + "->", result); // 左
if (cur->right) traversal(cur->right, path + "->", result); // 右
}
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
string path;
if (root == NULL) return result;
traversal(root, path, result);
return result;
}
};
3.左叶子之和 leetcode
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if ( root == NULL ) return 0;
if ( root -> right == NULL && root -> left == NULL ) return 0;
int leftnum = sumOfLeftLeaves( root -> left );
if ( root -> left != NULL && root -> left -> left == NULL && root -> left -> right == NULL ) leftnum = root -> left -> val;
int rightnum = sumOfLeftLeaves( root -> right );
int sum = leftnum + rightnum;
return sum;
}
};
判断当前节点是不是左叶子是无法判断的,必须要通过节点的父节点来判断其左孩子是不是左叶子。
如果该节点的左节点不为空,该节点的左节点的左节点为空,该节点的左节点的右节点为空,则找到了一个左叶子
jiangjiang