LintCode Binary Tree Maximum Node二叉樹的最大節點

Find the maximum node in a binary tree, return the node.

樣例
給出如下一棵二叉樹:

 1

/
-5 2
/ \ /
0 3 -4 -5
返回值為 3 的節點。

分析

簡單的遞歸思路,不過注意為空的情況,所以最好將為空的點的值設為最小值

代碼

public class Solution {
    /**
     * @param root the root of binary tree
     * @return the max ndoe
     */
    public TreeNode maxNode(TreeNode root) {
        if(root == null)
            return null;
        
        return getMaxNode(root);
    }
    
    public TreeNode getMaxNode(TreeNode root) {
        if(root == null)
            return new TreeNode(Integer.MIN_VALUE);
        
        TreeNode left = getMaxNode(root.left);
        TreeNode right = getMaxNode(root.right);
        
        if(root.val >= right.val && root.val >= left.val)
            return root;
        if(left.val >= right.val && left.val >= root.val)
            return left;
        return right;
    }    
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容