543. Binary Tree diameter Golang depth-first search dfs a daily problem

543. Binary Tree diameter

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.

Example:
given binary tree

      1
     / \
    2   3
   / \     
  4   5    

Return 3, which is the path length [4,2,1,3] or [5,2,1,3].

Note: the path length between two nodes is represented by the number of edges therebetween.

Thinking

dfs depth required to traverse all nodes of each node, and then updates the maximum diameter according to the depth.
The very beginning I declare the global variable initialization, after depth (root) directly in the main in return.
However, this use case has been could not pass.
depth (root )
I do not know what this means empty tree, I follow diameterOfBinaryTree (nil) to test the result is 0, and how wrong this is not 3 ah, this output confusing.
Solve the case:

 var(
	maxDiameter=0
)
func diameterOfBinaryTree(root *TreeNode) int {
	depth (root )
	return maxDiameter
}

I started this is the definition and use maxDiameter, please note that only a global variable is initialized when it is declared. And leetcode test series used in the embodiment of a program, so the value is a next initial value used in maxDiameter embodiment maxDiameter at the end of the use case .
To avoid such errors, we need to initialize before each seeking the maximum diameter.
Of course, you can also choose this way to record the maximum radius with depth (root * TreeNode, * maxDiam int), this mass participation and the way to avoid this problem.

My answer

Here Insert Picture Description

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
 var(
	maxDiameter int
)
func diameterOfBinaryTree(root *TreeNode) int {
    maxDiameter=1
	depth (root )
	return maxDiameter-1
}
func depth (root *TreeNode) int{
	if root==nil{
		return 0
	}
	left:=depth(root.Left)
	right:=depth(root.Right)
	if left+right+1>maxDiameter{
		maxDiameter=left+right+1
	}
	if left>right{
		return left+1
	}else{
		return right+1
	}
}
Published 38 original articles · won praise 0 · Views 1033

Guess you like

Origin blog.csdn.net/Cyan1956/article/details/104769421