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<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);  
        }  
    }  
}  
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容