110.平衡二叉树
代码
示例代码
class Solution { public: // 返回以该节点为根节点的二叉树的高度,如果不是平衡二叉树了则返回-1 int getHeight(TreeNode* node) { if (node == NULL) { return 0; } int leftHeight = getHeight(node->left); if (leftHeight == -1) return -1; int rightHeight = getHeight(node->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. 二叉树的所有路径*
代码
示例代码
// 版本一 class Solution { private: void traversal(TreeNode* cur, vector<int>& path, vector<string>& result) { path.push_back(cur->val); // 中,中为什么写在这里,因为最后一个节点也要加入到path中 // 这才到了叶子节点 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<string> result; vector<int> path; if (root == NULL) return result; traversal(root, path, result); return result; } };
思路
本题关键点在于终止条件和回溯处理。
404.左叶子之和
代码
示例代码
class Solution { public: void travel(TreeNode* cur, int& result) { if (cur == nullptr) return; // 检查左子节点是否为叶子节点 if (cur->left && !cur->left->left && !cur->left->right) { result += cur->left->val; } // 递归左子树和右子树 travel(cur->left, result); travel(cur->right, result); } int sumOfLeftLeaves(TreeNode* root) { int result = 0; travel(root, result); return result; } };
思路
不要忘记判断左孩子是否是左叶子。