二叉树的最大节点公式?
在二叉树中寻找值最大的节点并返回。
给出如下一棵二叉树:
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.v