本系列的博客将围绕在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;
}
}
本文介绍了一种在二叉树中寻找值最大的节点的方法。通过递归地遍历左右子树,比较每个节点的值来确定最大节点。提供了一个具体的实现代码示例。
1281

被折叠的 条评论
为什么被折叠?



