110.平衡二叉树
分析:判断每个节点的左右子树的高度差小于等于1;所以首先需要求左右子树高度,再在父节点进行判断,故此采用后序遍历。
思路:后序遍历二叉树,从底部递归回来时加上高度
class Solution {
public:int judge(TreeNode*root){if(root==nullptr)return 0;int hl=judge(root->left);if(hl==-1) return -1;int hr=judge(root->right);if(hr==-1) return -1;if(abs(hr-hl)>1) return -1;return 1+max(hr,hl);}bool isBalanced(TreeNode* root) {//思路二:递归遍历每一个节点的左右子树高度,判断是否差值小于等于1if(root==nullptr)return true;return judge(root)==-1?false:true;}
257.二叉树的所有路径
思路:要找到每一个叶子节点,并且加上一路上的值,使用前序遍历;在遍历到left和right为空时添加路径
class Solution {
public:vector<string>nodes;void judge(TreeNode*root,string mid){if(root==nullptr)return;if(!mid.empty())//当mid中有值时mid+="->";mid+=to_string(root->val);if(root->left==nullptr && root->right==nullptr)nodes.push_back(mid);judge(root->left,mid);judge(root->right,mid);}vector<string> binaryTreePaths(TreeNode* root) {//这题需要从根结点开始遍历且加上val值,所以采用前序遍历string mid="";judge(root,mid);return nodes;}
};
404.左叶子之和
思路:直接递归遍历,判断到左叶子节点计数
class Solution {
public:int count=0;void judge(TreeNode*root,bool dis){//dis用来判断是左子节点还是右子节点if(root==nullptr)return;if(root->left==nullptr && root->right==nullptr && dis)//当该节点是左叶子节点时count+=root->val;judge(root->left,true);judge(root->right,false);}int sumOfLeftLeaves(TreeNode* root) {if(root->left==nullptr && root->right==nullptr)//考虑只有一个节点的情况return 0;judge(root,true);return count;}
};