[Lintcode]二叉树的最大节点 java实现

2017-11-06  本文已影响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 tree
     * @return: the max node
     */
    public TreeNode maxNode(TreeNode root) {
        ArrayList<TreeNode> result = new ArrayList<TreeNode>();  
        result.add(root);  
        search(root , result);  
        return result.get(0); 
        // write your code here
    }
    
     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);  
        }  
    }  
}
上一篇 下一篇

猜你喜欢

热点阅读