Programmer interview questions 100 (27)-depth of the binary tree [data structure]
19:53:28 | category:
Tree | label: programming employment
Job Search
Data Structure | large font size, small/medium subscription
Question: Enter the root node of a binary tree to find the depth of the tree. A tree path is formed from the root node to the leaf node. The longest path length is the depth of the tree.
For example, input binary tree:
10
/\
6 14
//\
4 12 16
Output depth 3 of the tree.
The node definition of the binary tree is as follows:
Struct sbinarytreenode
// A node of the Binary Tree
{
Int m_nvalue;
// Value of Node
Sbinarytreenode * m_pleft; // left child of Node
Sbinarytreenode * m_pright; // right child of Node
};
Analysis: This question essentially examines the traversal of Binary Trees.
The topic defines the depth of a tree. Of course, we can get all the paths of the tree according to this definition, so that we can get the longest path and its length. It is a little troublesome to write programs.
We can also understand the depth of the tree from another perspective. If a tree has only one node, its depth is 1. If the root node has only the left subtree but not the right subtree, the depth of the tree should be the depth of the Left subtree plus 1. Similarly, if the root node has only the right subtree but not the left subtree, the depth of the tree should be the depth of the right subtree plus 1. What if there is both the right subtree and the left subtree? The depth of the tree is that the depth of the left and right sub-trees is greater than the depth of the limit plus 1.
The above idea is easily implemented using recursive methods. You only need to slightly modify the traversal code. The reference code is as follows:
//////////////////////////////////////// ///////////////////////////////
// Get depth of a binary tree
// Input: ptreenode-the head of a binary tree
// Output: the depth of a binary tree
//////////////////////////////////////// ///////////////////////////////
Int treedepth (sbinarytreenode * ptreenode)
{
// The depth of a empty tree is 0
If (! Ptreenode)
Return 0;
// The depth of left sub-tree
Int nleft = treedepth (ptreenode-> m_pleft );
// The depth of right sub-tree
Int nright = treedepth (ptreenode-> m_pright );
// Depth is the Binary Tree
Return (nleft> nright )? (Nleft + 1): (nright + 1 );
}
This article has been included in the book "offoffoffer-famous enterprise interviewer excellent typical programming questions". There are some changes, and the analysis and explanations in this book are more detailed. Welcome.
This question has been indexed by the 9du online judge system. You are welcome to go to http://ac.jobdu.com/hhtproblems.php to test the code of the pipeline.
He Haitao, the blogger, has copyright to this blog article. For Network reprint, please specify the source http://zhedahht.blog.163.com /. To organize the publications, contact the author.