算法训练day17 LeetCode 110
算法训练day17 LeetCode 110.257.404
110平衡二叉树
题目
题解
-
当子树已经不平衡,直接返回-1.平衡则返回子数高度进行更高树间的高度比较
class Solution { public: int getHeight(TreeNode *node) { if (node == NULL) { return 0; } int left = getHeight(node->left); if (left == -1) return -1; int right = getHeight(node->right); if (right == -1) return -1; return abs(left - right) > 1 ? -1 : max(left, right) + 1; } bool isBalanced(TreeNode *root) { return getHeight(root) == -1 ? false : true; } };
257.二叉树的所有路径
题目
题解
-
递归~回溯
-
注意回溯,保证更换方向时能够正确记录路径
-
class Solution { private: void traversal(TreeNode *cur, vector<int> &path, vector<string> &result) { path.push_back(cur->val); if (cur->left == NULL && cur->right == NULL) { string sPath; for (int i = 0; i < path.size() - 1; i++) { sPath += to_string(path[i]); sPath += "->"; } sPath += to_string(path[path.size() - 1]); result.push_back(sPath); return; } if (cur->left) { traversal(cur->left, path, result); path.pop_back(); } if (cur->right) { traversal(cur->right, path, result); path.pop_back(); } } public: vector<string> binaryTreePaths(TreeNode *root) { vector<int> path; vector<string> result; if (root == NULL) return result; traversal(root, path, result); return result; } };
404。左叶子之和
题目
题解
-
判断是否为“左”叶子必须依靠父节点
-
处理"leftvalue"时不必将左叶子值累加,因为在单支上只有单词赋值操作发生,不必担心"leftvalue"值被覆盖
-
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; //此处不必累加,因为只有处于末端得左叶子结点才可以赋值给leftval } int rightvalue = sumOfLeftLeaves(root->right); int sum = leftvalue + rightvalue; return sum; } }

浙公网安备 33010602011771号