代码随想录day17 LeetCode 110. 平衡二叉树 257. 二叉树的所有路径 404. 左叶子之和
110. 平衡二叉树
注意概念
class Solution { public: int getHeight(TreeNode* root){ if(root==NULL)return 0; int leftHeight=getHeight(root->left); if(leftHeight==-1)return -1; int rightHeight= getHeight(root->right); if(rightHeight==-1)return -1; return abs(leftHeight-rightHeight)>1?-1:1+max(leftHeight,rightHeight); } bool isBalanced(TreeNode* root) { return getHeight(root)==-1? false:true; } };
257. 二叉树的所有路径
注意递归的参数,path不是引用,并没有影响回溯之后的path值,在外面并没有->,path只有当前层的数字,所以不用弹出。
class Solution { public: void traversal(TreeNode* &root,string path,vector<string>&result){ path+=to_string(root->val); if(root->left==NULL&&root->right==NULL){ result.push_back(path); return; } if(root->left){ traversal(root->left,path+"->",result); } if(root->right){ traversal(root->right,path+"->",result); } } vector<string> binaryTreePaths(TreeNode* root) { string path; vector<string>result; if(root==NULL)return {}; traversal(root,path,result); return result; } };
404. 左叶子之和
层序遍历法。
class Solution { public: int leftsum(TreeNode* root){ int sum=0; queue<TreeNode*>qe; if(root!=NULL)qe.push(root); while(!qe.empty()){ int size=qe.size(); for(int i=0;i<size;i++){ if(qe.front()->left){ if(qe.front()->left->right==NULL&&qe.front()->left->left==NULL){ sum+=qe.front()->left->val; } qe.push(qe.front()->left); } if(qe.front()->right)qe.push(qe.front()->right); qe.pop(); } } return sum; } int sumOfLeftLeaves(TreeNode* root) { if(root==NULL)return 0; return leftsum(root); } };
浙公网安备 33010602011771号