美文网首页
LintCode入门级-2

LintCode入门级-2

作者: ___shin | 来源:发表于2017-11-01 21:32 被阅读0次

描述:
在二叉树中寻找值最大的节点并返回。
样例:
给出如下一棵二叉树:

     1
   /   \
 -5     2
 / \   /  \
0   3 -4  -5 

返回值为 3 的节点。
实现:

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {  
    /** 
     * @param root the root of binary tree 
     * @return the max ndoe 
     */  
    public TreeNode maxNode(TreeNode root) {  
        // Write your code here  
        ArrayList<TreeNode> result = new ArrayList<TreeNode>();  
        result.add(root);  
        search(root , result);  
        return result.get(0);  
    }  
      
    public void search(TreeNode root , ArrayList<TreeNode> result){  
        if(root == null){  
            return ;  
        }  
        if(result.get(0).val < root.val){  
            result.set(0 , root);  
        }  
        if(root.left != null){  
            search(root.left , result);  
        }  
        if(root.right != null){  
            search(root.right , result);  
        }  
    }  
}  

相关文章

  • LintCode入门级-2

    描述:在二叉树中寻找值最大的节点并返回。样例:给出如下一棵二叉树: 返回值为 3 的节点。实现:

  • LintCode入门级-3

    描述:给一组整数,按照升序排序,使用选择排序,冒泡排序,插入排序或者任何 O(n2) 的排序算法。样例:对于数组 ...

  • LintCode入门级-1

    描述:实现一个矩阵类Rectangle,包含如下的一些成员变量与函数:1.两个共有的成员变量 width 和 he...

  • LintCode入门级-4

    描述:删除链表中等于给定值val的所有节点。样例:给出链表 1->2->3->3->4->5->3, 和 val ...

  • LintCode入门级-5

    描述:查找斐波纳契数列中第 N 个数。 所谓的斐波纳契数列是指:前2个数是 0 和 1 。第 i 个数是第 i-1...

  • [入门级]lintcode--刷题

    第一题 第二题 第三题 第四题 第五题 第六题

  • 程序员常用的刷题网站

    1、Lintcode Lintcode.com——LintCode网站是国内较大的在线编程&测评网站。此网站提供各...

  • Singleton

    lintcode: http://lintcode.com/en/problem/singleton/ Java ...

  • 817. Range Sum Query 2D - Mutabl

    link: https://www.lintcode.com/problem/range-sum-query-2d...

  • 二叉树非递归遍历——已通过LintCode

    先序遍历 LintCode题目链接 中序遍历 LintCode题目链接 后序遍历 LintCode题目链接由于在L...

网友评论

      本文标题:LintCode入门级-2

      本文链接:https://www.haomeiwen.com/subject/svhnpxtx.html