课程: Java Algorithms
今天就学习课程吧!
今天就开通帐号,24,700 门业界名师课程任您挑!
Solution: Find height of binary tree
- [Instructor] Let's calculate the height of a tree. We'll start with the base case where the root of the tree is null. If the root is null, then the height of the tree is zero because there are no nodes in the tree. If the root is not null, then we'll need to account for it in our height. The tree must be at least one in height. Now this works if the height is actually one, but a given root can have left and right subtrees. In order to calculate the full height of the tree, we need to take these subtrees into account. We can do that by using our function recursively. We'll calculate the height of the left subtree by calling the same findHeight function with root.left. This will calculate the height of the left subtree. Now we can do the same thing for the right. So we have the height of the right and left subtrees. The total height of the tree will be this level plus the maximum of the subtree levels. That's our…
随堂练习,边学边练
下载课堂讲义。学练结合,紧跟进度,轻松巩固知识。