LintCode二叉樹的最大節點
阿新 • • 發佈:2019-01-27
本系列的部落格將圍繞在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;
}
}