在二叉树中寻找值最大的节点并返回。
给出如下一棵二叉树:
1
/ -5 2
/ \ / 0 3 -4 -5
返回值为 3 的节点。
看到这道题第一个反应就是对于二叉树来说最常用的方式就是递归,所以本题也不例外。
思路就是递归左子树,取得左面的最大值,在递归柚子树,取得右边的最大值,然后root,left,right三个节点做比较
Java:
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/*
* @param root: the root of tree
* @return: the max node
*/
public TreeNode maxNode(TreeNode root) {
if(root == null)//首先判断root节点是否为空,空就直接返回
return null;
TreeNode left = root,right = root;//将root值付给left和right,因为三点的val做比较,防止出现left或right在val比较时出现null异常(卡在这里很久)
if(root.left != null)
left = maxNode(root.left);//递归获取左子树最大node
if(root.right != null)
right = maxNode(root.right);//递归获取右子树最大node
TreeNode temp = left.val > root.val ? left:root;先做比较左子树和root取得最大值
return right.val > temp.val ?right:temp;//在做最大值和右子树比较
// return temp;
}
}
python
class Solution: """ @param: root: the root of tree @return: the max node """ def maxNode(self, root): if root is None: return None left = right = root; if root.left is not None: left = self.maxNode(root.left) if root.right is not None: right = self.maxNode(root.right) temp = root #因为python不支持三目运算符这里比java代码用简便的方式实现 if left.val > root.val: temp = left if right.val > temp.val: temp = right return temp