本文主要是介绍代码随想录算法训练营第十七天|LeetCode110 平衡二叉树、LeetCode257 二叉树的所有路径,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题1:
指路:LeetCode110 平衡二叉树
思路与代码:
左右子树的高度差小于等于1。对于这个题,递归比迭代方便太多,我也想过迭代,但是我没有写出来,大家可以自己试一下。递归代码如下:
class Solution {
public://递归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;int ans = abs(leftHeight - rightHeight);if (ans > 1) return -1; // 绝对值超过1符合条件else return 1 + max(leftHeight, rightHeight);/* return abs(leftHeight - rightHeight) > 1 ? -1 : 1 + max(leftHeight, rightHeight);*/} bool isBalanced(TreeNode* root) {if (getHeight(root)== -1) return false;return true;/*return getHeight(root) == -1 ? false : true;*/}
};
题2:
指路:LeetCode257 二叉树的所有路径
思路与代码:
递归进行前序遍历,找到子节点记录路径之后回溯回退路径。我还没会呢,先看看代码吧。
class Solution {
private:void treversal(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) {treversal(cur->left, path, result);path.pop_back();}if (cur->right) {treversal(cur->right, path, result);path.pop_back();}}public:vector<string> binaryTreePaths(TreeNode* root) {vector<string> result;vector<int> path;if (root == NULL) return result;treversal(root, path, result);return result;}
};
这篇关于代码随想录算法训练营第十七天|LeetCode110 平衡二叉树、LeetCode257 二叉树的所有路径的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!