zoukankan      html  css  js  c++  java
  • 二叉树删除节点,(查找二叉树最大值节点)

    从根节点往下分别查找左子树和右子树的最大节点,再比较左子树,右子树,根节点的大小得到结果,在得到左子树和右子树最大节点的过程相似,因此可以采用递归的

    1. //树节点结构  
    2. public class TreeNode {  
    3.     TreeNode left;  
    4.     TreeNode right;  
    5.     int val;  
    6.     TreeNode(int val){  
    7.         this.val = val;  
    8.     }  
    9. }  
    10. public class Solution {  
    11.     /** 
    12.      * @param root 传入根节点 
    13.      * @return 返回最大结果 
    14.      */  
    15.     public static TreeNode maxNode(TreeNode root){  
    16.         //当再无子节点,返回当前节点  
    17.         if (root == null) {  
    18.             return root;  
    19.         }   
    20.           
    21.         TreeNode left = maxNode(root.left);//递归得到左子树最大值  
    22.         TreeNode right = maxNode(root.right);//递归得到右子树的最大值  
    23.         return max(root,max(left,right));//返回左节点,根节点,右节点的最大值  
    24.           
    25.     }  
    26.     public static TreeNode max(TreeNode a,TreeNode b) {  
    27.         if (a == null) {  
    28.             return b;  
    29.         }  
    30.         if (b == null) {  
    31.             return a;  
    32.         }  
    33.         if (a.val > b.val) {  
    34.             return a;  
    35.         }  
    36.         return b;  
    37.     }  
    38.     public static void main(String[] args) {  
    39.         TreeNode t1 = new TreeNode(1);  
    40.         TreeNode t2 = new TreeNode(-5);  
    41.         TreeNode t3 = new TreeNode(3);  
    42.         TreeNode t4 = new TreeNode(1);  
    43.         TreeNode t5 = new TreeNode(2);  
    44.         TreeNode t6 = new TreeNode(-4);  
    45.         TreeNode t7 = new TreeNode(-5);  
    46.         t1.left = t2;t1.right = t5;  
    47.         t2.left = t3;t2.right = t4;  
    48.         t5.left = t6;t5.right = t7;  
    49.         System.out.println(Solution.maxNode(t1).val);  
    50.     }  
    51. }  
  • 相关阅读:
    地区表设计(包括数据插入) Dear
    本博客的内容
    linux msn
    相关的一些技术
    相关的一些产品
    考第一名的学生的发言
    AIX&LINUX操作系统调优
    shell for循环
    自动化测试
    DB2数据库日志
  • 原文地址:https://www.cnblogs.com/Darkqueen/p/9165794.html
Copyright © 2011-2022 走看看