网站建设需求模板下载,网站宣传推广,创网站,沈阳微信网站制作110.平衡二叉树 文档链接#xff1a;[代码随想录] 题目链接#xff1a;:110.平衡二叉树 题目#xff1a; 给定一个二叉树#xff0c;判断它是否是 平衡二叉树 注意#xff1a; 判断两棵子树高度差是否大于1
class Solution {
public:int result;bool isBalanced(TreeNode…110.平衡二叉树 文档链接[代码随想录] 题目链接:110.平衡二叉树 题目 给定一个二叉树判断它是否是 平衡二叉树 注意 判断两棵子树高度差是否大于1
class Solution {
public:int result;bool isBalanced(TreeNode* root) {int res count(root);if(res -1) return false;return true;}int count(TreeNode* node){if(node NULL)return 0;int leftDepth count(node - left);if(leftDepth -1) return -1;int rightDepth count( node - right);if(rightDepth -1) return -1;int result abs(leftDepth - rightDepth) 1 ? -1 : 1 max(leftDepth,rightDepth);return result;}
};257. 二叉树的所有路径 文档链接[代码随想录] 题目链接:110.平衡二叉树 题目 给你一个二叉树的根节点 root 按 任意顺序 返回所有从根节点到叶子节点的路径。叶子节点 是指没有子节点的节点。
class Solution {
private:void traversal(TreeNode* node,vectorint path,vectorstring result){path.push_back(node - val);if(node - left NULL node - right NULL){string s;for(int i 0; i path.size() - 1; i){s to_string(path[i]);s -;}s to_string(path[path.size() - 1]);result.push_back(s);return;}if(node - left){traversal(node - left, path, result);path.pop_back();}if(node - right){traversal(node - right, path, result);path.pop_back();}}
public:vectorstring binaryTreePaths(TreeNode* root) {vectorint path;vectorstring res;if (root NULL) return res;traversal(root,path,res);return res;}
};404.左叶子之和 文档链接[代码随想录] 题目链接:110.平衡二叉树 状态 这题好难理解递归还是不太懂 题目 给定二叉树的根节点 root 返回所有左叶子之和。
class Solution {
public:int sumOfLeftLeaves(TreeNode* root) {if (root NULL) return 0;if (root-left NULL root-right NULL) return 0;int leftValue sumOfLeftLeaves(root-left); // 左if (root-left !root-left-left !root-left-right) { // 左子树就是一个左叶子的情况leftValue root-left-val;}int rightValue sumOfLeftLeaves(root-right); // 右int sum leftValue rightValue; // 中return sum;}
};