题解 | #牛群的最大高度#

牛群的最大高度

https://www.nowcoder.com/practice/f745023c5ac641c9914a59377dacdacf

题目考察的知识点:二叉树的遍历,前序遍历(Preorder Traversal 亦称先序遍历)——访问根结点的操作发生在遍历其左右子树之前。 中序遍历(Inorder Traversal)——访问根结点的操作发生在遍历其左右子树之中(间)。 后序遍历(Postorder Traversal)——访问根结点的操作发生在遍历其左右子树之后。

题目解答方法的文字分析:遍历这棵树,将每次的返回值与自身结点的值相比,返回较大的值。

本题解析所用的编程语言:c++

int findMaxHeight(TreeNode* root)
{
    // write code here
    if (root == nullptr)
        return -1;

    int max = 0;
    if (root->left) max = findMaxHeight(root->left);
    if (root->right) max = findMaxHeight(root->right);

    return root->val > max ? root->val : max;

}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
1
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务