LintCode入门级-2

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

     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 result = new ArrayList();  
        result.add(root);  
        search(root , result);  
        return result.get(0);  
    }  
      
    public void search(TreeNode root , ArrayList 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)