第9天--算法(折绳子问题,判断某二叉树是否为平衡二叉树,判断某二叉树是否为搜索二叉树)

折绳子问题(一根绳子,自下向上折叠n次,依次打印展开之后折痕的凹凸)

public void process(int i,int n,boolean flag) {      //  i : 当前层数,n : 最多层数

  if(i > n) {

    return;

  }

  process(i + 1,n,true);

  System.out.print(flag ? "凹" : "凸");

  process(i + 1,n,false);

}

 平衡二叉树

/**

 * Definition for a binary tree node.

 * public class TreeNode {

 *     int val;

 *     TreeNode left;

 *     TreeNode right;

 *     TreeNode(int x) { val = x; }

 * }

 */

class Solution {

    public boolean isBalanced(TreeNode root) {

        return process(root).flag;

    }

    public Info process(TreeNode root) {

        if(root == null) {

            return new Info(0,true);

        }

        Info left = process(root.left);

        Info right = process(root.right);

        int height = Math.max(left.height,right.height) + 1;

        if(!left.flag || !right.flag) {

            return new Info(0,false);

        }else {

            if(Math.abs(left.height - right.height) > 1) {

                return new Info(0,false); 

            }else {

                return new Info(height,true);

            }

        }

    }

}

class Info {

    int height;

    boolean flag;

    public Info(int height,boolean flag) {

        this.height = height;

        this.flag = flag;

    }

}

搜索二叉树

/**

 * Definition for a binary tree node.

 * public class TreeNode {

 *     int val;

 *     TreeNode left;

 *     TreeNode right;

 *     TreeNode() {}

 *     TreeNode(int val) { this.val = val; }

 *     TreeNode(int val, TreeNode left, TreeNode right) {

 *         this.val = val;

 *         this.left = left;

 *         this.right = right;

 *     }

 * }

 */

class Solution {

    public boolean isValidBST(TreeNode root) {

        return process(root).isBST;

    }

    public Info process(TreeNode root) {

        if(root == null) {

            return null;

        }

        Info left = process(root.left);

        Info right = process(root.right);

        int max = root.val;

        int min = root.val;

        boolean isBST = true;

        if((left != null && !left.isBST) || (right != null && !right .isBST)) {

            isBST = false;

        }

        if((left != null && left.max >= max) || (right != null && right.min <= min)) {

            isBST = false;

        }

        if(left != null) {

            max = Math.max(max,left.max);

            min = Math.min(min,left.min);

        }

        if(right != null) {

            max = Math.max(max,right.max);

            min = Math.min(min,right.min);

        }

        return new Info(max,min,isBST);

    }

}

class Info {

    int max;

    int min;

    boolean isBST;

    public Info(int max,int min,boolean isBST) {

        this.max = max;

        this.min = min;

        this.isBST = isBST;

    }

}

posted @ 2021-11-02 15:59  现在开始努力  阅读(48)  评论(0)    收藏  举报