二叉树删除节点,(查找二叉树最大值节点)
从根节点往下分别查找左子树和右子树的最大节点,再比较左子树,右子树,根节点的大小得到结果,在得到左子树和右子树最大节点的过程相似,因此可以采用递归的
- //树节点结构
- public class TreeNode {
- TreeNode left;
- TreeNode right;
- int val;
- TreeNode(int val){
- this.val = val;
- }
- }
- public class Solution {
- /**
- * @param root 传入根节点
- * @return 返回最大结果
- */
- public static TreeNode maxNode(TreeNode root){
- //当再无子节点,返回当前节点
- if (root == null) {
- return root;
- }
- TreeNode left = maxNode(root.left);//递归得到左子树最大值
- TreeNode right = maxNode(root.right);//递归得到右子树的最大值
- return max(root,max(left,right));//返回左节点,根节点,右节点的最大值
- }
- public static TreeNode max(TreeNode a,TreeNode b) {
- if (a == null) {
- return b;
- }
- if (b == null) {
- return a;
- }
- if (a.val > b.val) {
- return a;
- }
- return b;
- }
- public static void main(String[] args) {
- TreeNode t1 = new TreeNode(1);
- TreeNode t2 = new TreeNode(-5);
- TreeNode t3 = new TreeNode(3);
- TreeNode t4 = new TreeNode(1);
- TreeNode t5 = new TreeNode(2);
- TreeNode t6 = new TreeNode(-4);
- TreeNode t7 = new TreeNode(-5);
- t1.left = t2;t1.right = t5;
- t2.left = t3;t2.right = t4;
- t5.left = t6;t5.right = t7;
- System.out.println(Solution.maxNode(t1).val);
- }
- }