代码随想录算法训练营第十七天| 110.平衡二叉树、257. 二叉树的所有路径、404.左叶子之和

110.平衡二叉树

https://leetcode.cn/problems/balanced-binary-tree/

思路:采取后序遍历思想,先后获得两个左右子树的深度,不断递归检查每个节点的左右子树深度相差是否超过1,如果超过的话说明二叉树不平衡。

#include<cmath>
class Solution {
public:
    int getHeight(TreeNode* cur){
        if(!cur) return 0;
        int leftHeight = getHeight(cur->left);
        int rightHeight = getHeight(cur->right);
        if(leftHeight == -1 || rightHeight == -1) return -1;
        if(abs(leftHeight - rightHeight) > 1) return -1;
        return max(leftHeight, rightHeight) + 1;
    }
    bool isBalanced(TreeNode* root) {
        if(getHeight(root) == -1) return false;
        return true;
    }
};

257. 二叉树的所有路径

https://leetcode.cn/problems/binary-tree-paths/

思路:采用后序遍历思想,寻找每一条路径,但比起单纯的遍历要多使用一个栈来储存已经走过的路径。

递归法:

class Solution {
public:
	void btr(TreeNode* cur, vector<string>& result, string path) {
		if (!cur) return;
		if (!cur->left && !cur->right) {
			result.push_back(path);
		}
		if (cur->left) btr(cur->left, result, path + "->" + to_string(cur->left->val));
		if (cur->right) btr(cur->right, result, path + "->" + to_string(cur->right->val));
	}
	vector<string> binaryTreePaths(TreeNode* root) {
		if (!root) return {};
		vector<string> result;
		btr(root, result, to_string(root->val));
		return result;
	}
};

迭代法:

class Solution {
public:
	vector<string> binaryTreePaths(TreeNode* root) {
		vector<string> result;
		stack<string> allPaths;
		stack<TreeNode*> stk;
		if (root) {
			stk.push(root);
			allPaths.push(to_string(root->val));
		}
		while (!stk.empty()) {
			TreeNode* cur = stk.top();
			stk.pop();
			string nowPath = allPaths.top();
			allPaths.pop();
			if (!cur->left && !cur->right) {
				result.push_back(nowPath);
			}
			if (cur->right) {
				stk.push(cur->right);
				allPaths.push(nowPath + "->" + to_string(cur->right->val));
			}
			if (cur->left) {
				stk.push(cur->left);
				allPaths.push(nowPath + "->" + to_string(cur->left->val));
			}
		}
		return result;
	}
};

404.左叶子之和

https://leetcode.cn/problems/sum-of-left-leaves/

遍历顺序无所谓,重要的是判断某个节点是不是左叶子节点。

class Solution {
public:
	void sum(TreeNode* cur, int& result) {
		if (!cur) return;
		if (cur->left && !cur->left->left && !cur->left->right) result += cur->left->val;
		sum(cur->left, result);
		sum(cur->right, result);
	}
	int sumOfLeftLeaves(TreeNode* root) {
		if (!root) return 0;
		int result = 0;
		sum(root, result);
		return result;
	}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值