LintCode二叉树的最大节点

xiaoxiao2021-02-27  197

本系列的博客将围绕在LintCode网站上的算法题进行编写,主要记录一下在刷题过程中的一些思路、想法,遇到困难时也会参考一些网上的资源。

目录

目录题目描述解题思路代码块


题目描述

在二叉树中寻找值最大的节点并返回。 样例:             1           /    \         -5      2       /  \     /   \     0     3 -4    -5

解题思路

求解这个问题就像是求解一个数组的最大值一样,要将当前的最大的依次与后面的值进行比较,从而得到最大的值,唯一的不同的点就是这里使用的是树结构,所以要依次比较左右子树。

代码块

具体的实现代码如下:

public class Solution { /** * @param root the root of binary tree * @return the max ndoe */ public TreeNode maxNode(TreeNode root) { // Write your code here if(root == null){ return null; } TreeNode max = root; TreeNode temp; if(root.left == null && root.right == null){ max = root; } if(root.left != null){ temp = maxNode(root.left); if(max.val < temp.val){ max = temp; } } if(root.right != null){ temp = maxNode(root.right); if(max.val < temp.val){ max = temp; } } return max; } }
转载请注明原文地址: https://www.6miu.com/read-10597.html

最新回复(0)