204

问答题 204 /413

手写代码:求全体二叉树节点最大值

参考答案

参考回答:

public int maxTreeNode(TreeNode root) {
if (root.left == null && root.right == null) {
return root.val;
} else {
if (root.left != null && root.right != null) {
return root.val > maxTreeNode(root.left) ? (root.val > maxTreeNode(root.right) ? root.val
: maxTreeNode(root.right))
: (maxTreeNode(root.left) > maxTreeNode(root.right) ? maxTreeNode(root.left)
: maxTreeNode(root.right));
} else if (root.left == null && root.right != null) {
return root.val > maxTreeNode(root.right) ? root.val
: maxTreeNode(root.right);
} else {
return root.val > maxTreeNode(root.left) ? root.val
: maxTreeNode(root.left);
}
}
}