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中的一道入门题,我的思路是采用递归的思想获得左子树和右子树,然后将根节点的值与左子树和右子树的根节点的值相比较,值最大的节点赋值给根节点,然后返回根节点。

 

转载于:https://www.cnblogs.com/zwxblog/p/7735095.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值