Some common problems and implement classical algorithms

TopK algorithm:

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

Binary tree Diameter:

leetcode543:

Given a binary tree, you need to calculate the length of its diameter. A binary tree is the maximum length of the diameter of any two nodes in the path lengths. This path may pass through the root.

Ideas:

  Simple binary tree traversal, the left and right child nodes according to the number of nodes of the tree to calculate the maximum length of the current tree, and updates the global maximum length. Core return is about the longest sub-tree and a root node and.

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;
};

 Binary tree expands to list:

  leetcode114:

  Given a binary tree, place it expands the list.

  

Guess you like

Origin www.cnblogs.com/lxy-xf/p/11345095.html
Recommended