二叉树的最大节点

 1 public class Solution {
 2     /*
 3      * @param root: the root of tree
 4      * @return: the max node
 5      */
 6     public TreeNode maxNode(TreeNode root) {
 7         // write your code here
 8         List<TreeNode> max = new ArrayList<TreeNode>();
 9         max.add(root);
10         if(root != null) {
11             findMax(max, root);
12         }
13         return max.get(0);
14     }
15     
16     public void findMax(List<TreeNode> max, TreeNode node) {
17         if (node.val > max.get(0).val) {
18             max.set(0, node);
19         }
20         if (node.left != null) {
21             findMax(max, node.left);
22         }
23         if (node.right != null) {
24             findMax(max, node.right);
25         }
26     }
27 }

有return的递归较麻烦,所以用ArrayList存储最大节点,使用void递归。 

posted @ 2017-11-08 11:02  南瓜1996  阅读(295)  评论(0编辑  收藏  举报