forked from cherryljr/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary Tree Maximum Node.java
More file actions
47 lines (40 loc) · 898 Bytes
/
Binary Tree Maximum Node.java
File metadata and controls
47 lines (40 loc) · 898 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// 属于简单的问题,可以使用遍历该树,然后得出最大值。
// 也可以使用分治法来解决该问题
/*
Description:
Find the maximum node in a binary tree, return the node.
Example:
Given a binary tree:
1
/ \
-5 2
/ \ / \
0 3 -4 -5
return the node with value 3.
Tags
Binary Tree
*/
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 root;
TreeNode left = maxNode(root.left);
TreeNode right = maxNode(root.right);
return max(root, max(left, right));
}
TreeNode max(TreeNode a, TreeNode b) {
if (a == null)
return b;
if (b == null)
return a;
if (a.val > b.val) {
return a;
}
return b;
}
}