LintCode之二叉树的最大节点

题目描述:

我的代码:

 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         TreeNode l;
 9         TreeNode r;
10         if(root == null) {
11             return null;
12         }
13         //获得左子树的根节点
14         l = maxNode(root.left);
15         //获得右子树的根节点
16         r = maxNode(root.right);
17         if(l != null) {
18             //如果根节点的值小于左子树的根节点的值,就交换
19             if(root.val < l.val) {
20                 root = l;
21             }
22         }
23         if(r != null) {
24             //如果根节点的值小于右子树的根节点的值,就交换
25             if(root.val < r.val) {
26                 root = r;
27             }
28         }
29         //返回最大值
30         return root;
31     }
32 }

总结:该题是LintCode中的一道入门题,我的思路是采用递归的思想获得左子树和右子树,然后将根节点的值与左子树和右子树的根节点的值相比较,值最大的节点赋值给根节点,然后返回根节点。

 

posted @ 2017-10-26 08:31  zwt3  阅读(1247)  评论(1编辑  收藏  举报