leetcode(二) #104 #111 #107

#104 二叉树的最大深度

class Solution {
public:
    int maxDepth(TreeNode* root) 
	{
		if (root == NULL)
			return 0;
		int ans = getMaxDepth(root);
		return ans;
	}

	int getMaxDepth(TreeNode* root)
	{
		if (root->left == NULL&&root->right == NULL)
			return 1;
		else
		{
			int ld = 0, rd = 0;
			if (root->left != NULL)
				ld = getMaxDepth(root->left);
			if (root->right != NULL)
				rd = getMaxDepth(root->right);
			return 1 + (ld > rd ? ld : rd);
		}
	}
};

#111 二叉树的最小深度

class Solution {
public:
    int minDepth(TreeNode* root) 
	{
		if (root == NULL)
			return 0;
		return getMinDepth(root);
	}
	int getMinDepth(TreeNode* root)
	{
		if (root->left == NULL&&root->right == NULL)
			return 1;
		else
		{
			int ld = INT_MAX, rd = INT_MAX;
			if (root->left != NULL)
				ld = getMinDepth(root->left);
			if (root->right != NULL)
				rd = getMinDepth(root->right);
			return 1 + (ld < rd ? ld : rd);
		}
	}
};

#107 二叉树的层次遍历II

class Solution {
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) 
	{
		vector<vector<int>> ans;
		if (root == NULL)
			return ans;

		helper(ans, root, 0);
        reverse(ans.begin(), ans.end());
        return ans;
	}

	void helper(vector<vector<int>>& ans, TreeNode* root, int depth)
	{
		if (depth >= ans.size())
			ans.push_back(vector<int>());
		
		ans[depth].push_back(root->val);
		if (root->left != NULL)
			helper(ans, root->left, depth + 1);
		if (root->right != NULL)
			helper(ans, root->right, depth + 1);
	}
};

猜你喜欢

转载自blog.csdn.net/N_Young/article/details/82559753
107