The depth of the Binary Tree "Sword refers to offer" and the Binary Tree "Sword refers to offer"
[Disclaimer: All Rights Reserved. indicate the source for reprinting. Do not use it for commercial purposes. Contact mailbox: libin493073668@sina.com]
Question link: http://www.nowcoder.com/practice/435fb86331474282a3499955f0a41e8b? Rp = 2 & ru =/ta/coding-interviews & qru =/ta/coding-interviews/question-ranking
Description
Enter 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.
Ideas
Finding the depth of a tree is a simple recursive idea. Just layer-by-layer recursive statistics.
/* Struct TreeNode {int val; struct TreeNode * left; struct TreeNode * right; TreeNode (int x): val (x), left (NULL), right (NULL) {}}; */class Solution {public: int TreeDepth (TreeNode * pRoot) {if (pRoor = nullptr) return 0; int left = TreeDepth (pRoot-> left ); int right = TreeDepth (pRoot-> right); return (left> right )? (Left + 1) :( right + 1 );}};
Copyright Disclaimer: This article is the original article of the blogger. If it is reproduced, please indicate the source