一些常见的经典算法题及实现

TopK算法:

https://www.cnblogs.com/lxy-xf/p/11338652.html

二叉树的直径:

leetcode543:

给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。

思路:

  很简单的遍历二叉树,根据子节点左右树的节点数来计算当前树下的最长长度,并更新全局最长长度。Core返回的是左右子树最长的一棵和根节点的和。

class Solution {
public:
    int diameterOfBinaryTree(TreeNode* root) {
		if(!root)
			return 0;
		g_max=INT_MIN;
		Core(root);
		return g_max;
    }
private:
	int Core(TreeNode* root)
	{
		if(!root)
			return 0;
		int left=Core(root->left);
		int right=Core(root->right);
		if(left+right+1>g_max)
			g_max=left+right;
		int result=(left>right)?left:right;
		return result+1;
	}
	int g_max;
};

 二叉树展开为链表:

  leetcode114:

  给定一个二叉树,原地将它展开为链表。

  

猜你喜欢

转载自www.cnblogs.com/lxy-xf/p/11345095.html