代码随想录第十七天
平衡二叉树的判断
平衡二叉树是指二叉树中任意节点的子树的高度之差小于等于1,使用后序遍历先得到左右子树的高度,然后返回1+较大高度
代码如下:
class Solution
{
public:
int balanceTree(TreeNode* root)
{
if (root == NULL)
return 0;
int leftHeight = balanceTree(root->left);
if (leftHeight == -1)
return -1;
int rightHeight = balanceTree(root->right);
if (rightHeight == -1)
return -1;
if (abs(leftHeight - rightHeight) > 1)
return -1;
else
{
return (1 + max(leftHeight, rightHeight));
}
}
}
打印二叉树的所有路径
使用前序遍历的方法,到叶子结点的时候记录一次路径
代码如下
class Solution
{
public:
vector<int> path;
vector<string> result;
void treeVersale(TreeNode* root, vector<int>& path, vector<string>& result)
{
path.push_back(root->value);
if (root->left==NULL&&root->right==NULL)
{
int size = path.size();
string spath;
for (size_t i = 0; i < size-1; i++)
{
spath += to_string(path[i]);
spath += "->";
}
spath += to_string(path[size - 1]);
result.push_back(spath);
return;
}
if (root->left)
{
treeVersale(root->left, path, result);
path.pop_back();
}
if (root->right)
{
treeVersale(root->right, path, result);
path.pop_back();
}
return;
}
vector<string> binaryTreePaths(TreeNode* root)
{
treeVersale(root, path, result);
return result;
}
}
计算左叶子之和
使用后序遍历,返回子树中符合条件的叶子之和
代码如下:
class Solution
{
public:
int leftTree(TreeNode* root)
{
if (root == NULL)
return 0;
int leftnum = leftTree(root->left);
if (root->left!=NULL&&root->left->left==NULL&&root->left->right==NULL)
{
leftnum = root->left->value;
}
int rightnum = leftTree(root->right);
return leftnum + rightnum;
}
}