【Lintcode】632. Binary Tree Maximum Node

题目地址:

https://www.lintcode.com/problem/binary-tree-maximum-node/description

给定一棵二叉树,寻找值最大的节点。

思路是分治法。如果是空树显然就返回null,否则先找左右子树的最大节点,然后和树根比一下即可。代码如下:

public class Solution {
    /*
     * @param root: the root of tree
     * @return: the max node
     */
    public TreeNode maxNode(TreeNode root) {
        // write your code here
        if (root == null) {
            return null;
        }
        
        TreeNode left = maxNode(root.left), right = maxNode(root.right);
        if (left == null && right == null) {
            return root;
        } else if (left == null) {
            return root.val > right.val ? root : right;
        } else if (right == null) {
            return root.val > left.val ? root : left;
        } else {
            if (root.val > Math.max(left.val, right.val)) {
                return root;
            } else {
                return left.val > right.val ? left : right;
            }
        }
    }
}

class TreeNode {
    int val;
    TreeNode left, right;
    TreeNode(int x) {
        val = x;
    }
}

时间复杂度 O ( n ) O(n) ,空间 O ( h ) O(h)

发布了387 篇原创文章 · 获赞 0 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_46105170/article/details/105467372
今日推荐