牛客算法之树(简单)

1.二叉树的最大深度

题目描述:

求给定二叉树的最大深度,
最大深度是指树的根结点到最远叶子结点的最长路径上结点的数量。

代码:
import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
     //递归方式
    public int maxDepth (TreeNode root) {
        // write code here
        if(root==null){
            return 0;
        }
        int leftDepth=maxDepth(root.left);
        int rightDepth=maxDepth(root.right);
        int res=Math.max(leftDepth,rightDepth);
        return res+1;
        
    }
    //通过链表
    public int maxDepth (TreeNode root) {
        // write code here
        if(root==null){
            return 0;
        }
        LinkedList<TreeNode> list=new LinkedList<>();
        list.offer(root);
        int level=0;
        int size=0;
        int cur=0;
        while(!list.isEmpty()){
            size=list.size();
            cur=0;
            while(cur<size){
                TreeNode node=list.poll();
                cur++;
                if(node.left!=null){
                    list.offer(node.left);
                }
                if(node.right!=null){
                    list.offer(node.right);
                }
            }
            level++;
        }
        return level;
        
    }
}

2.平衡二叉树:

题目描述:

输入一棵二叉树,判断该二叉树是否是平衡二叉树。
在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树
平衡二叉树(Balanced Binary Tree),具有以下性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。

代码:
public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        return process(root).isBalanced;
    }
    public class ReturnType{
        boolean isBalanced;
        int height;
        ReturnType(boolean isBalanced,int height){
            this.isBalanced=isBalanced;
            this.height=height;
        }
    }
    public ReturnType process(TreeNode root){
        if(root==null){
            return new ReturnType(true,0);
        }
        ReturnType lData=process(root.left);
        ReturnType rData=process(root.right);
        int height=Math.max(lData.height,rData.height)+1;
        boolean isBalanced=lData.isBalanced&&rData.isBalanced&&Math.abs(lData.height-rData.height)<2;
        return new ReturnType(isBalanced,height);
    }
}

3.判断二叉树是否对称

题目描述:

给定一棵二叉树,判断琪是否是自身的镜像(即:是否对称)
例如:下面这棵二叉树是对称的

代码:
import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return bool布尔型
     */
     //递归方法
    public boolean isSymmetric (TreeNode root) {
        // write code here
        if(root==null){
            return true;
        }
        return compare(root.left,root.right);
    }
    public boolean compare(TreeNode left,TreeNode right){
        if(left==null&&right==null){
            return true;
        }
        if(left==null||right==null){
            return false;
        }
        return left.val==right.val&&compare(left.left,right.right)&&compare(left.right,right.left);
    }

	//迭代
	public boolean isSymmetric (TreeNode root) {
        // write code here
        if(root==null){
            return true;
        }
        Queue<TreeNode> q=new LinkedList<>();
        q.offer(root.left);
        q.offer(root.right);
        while(!q.isEmpty()){
            TreeNode left=q.poll();
            TreeNode right=q.poll();
            if(left==null&&right==null){
                continue;
            }
            if(left==null||right==null){
                return false;
            }
            if(left.val!=right.val){
                return false;
            }
            q.offer(left.left);
            q.offer(right.right);
            q.offer(left.right);
            q.offer(right.left);
        }
        return true;
    }
}

4.二叉树中是否存在节点和为指定数

题目描述:

给定一个二叉树和一个值sum,判断是否有从根节点到叶子节点的节点值之和等于sum 的路径。

代码:
import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @param sum int整型 
     * @return bool布尔型
     */
    public boolean hasPathSum (TreeNode root, int sum) {
        // write code here
        if(root==null){
            return false;
        }
        Stack<TreeNode> q=new Stack<TreeNode>();
        HashSet<TreeNode> set=new HashSet<TreeNode>();
        q.push(root);
        int k=sum;
        while(!set.contains(root)){
            TreeNode cur=q.pop();
            sum-=cur.val;
            if(cur.right!=null){
                if(!set.contains(cur.right)){
                    q.push(cur.right);
                }
            }
            if(cur.left!=null){
                if(!set.contains(cur.left)){
                    q.push(cur.left);
                }
            }
            if(cur.left==null&&cur.right==null||cur.left==null&&set.contains(cur.right)||cur.right==null&&set.contains(cur.left)||set.contains(cur.left)&&set.contains(cur.right)){
                set.add(cur);
                if(cur.left==null&&cur.right==null){
                    if(sum==0){
                        return true;
                    }
                }
                q.clear();
                q.push(root);
                sum=k;
            }
        }
        return false;
    }
}

5.二叉搜索树的第k个结点

题目描述:

给定一棵二叉搜索树,请找出其中的第k小的TreeNode结点。

代码:
/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
import java.util.*;
public class Solution {
    PriorityQueue<TreeNode> priorityQueue=new PriorityQueue<>(new Comparator<TreeNode>(){
            public int compare(TreeNode o1,TreeNode o2){
                return o1.val-o2.val;
            }
        });
    TreeNode KthNode(TreeNode pRoot, int k) {
        pre(pRoot);
        TreeNode temp=null;
        for(int i=0;i<k;i++){
            temp=priorityQueue.poll();
        }
        return temp;
    }
    public void pre(TreeNode pRoot){
        if(pRoot==null){
            return;
        }
        priorityQueue.add(pRoot);
        pre(pRoot.left);
        pre(pRoot.right);
    }
}

6.二叉树的镜像

题目描述:

操作给定的二叉树,将其变换为源二叉树的镜像。

代码:
import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pRoot TreeNode类 
     * @return TreeNode类
     */
    public TreeNode Mirror (TreeNode pRoot) {
        // write code here
        if(pRoot==null){
            return pRoot;
        }
        TreeNode temp=pRoot.left;
        pRoot.left=pRoot.right;
        pRoot.right=temp;
        Mirror(pRoot.left);
        Mirror(pRoot.right);
        return pRoot;
    }
}

7.判断t1树中是否有与t2树拓扑结构完全相同的子树

题目描述:

给定彼此独立的两棵二叉树,判断 t1 树是否有与 t2 树拓扑结构完全相同的子树。
设 t1 树的边集为 E1,t2 树的边集为 E2,若 E2 等于 E1 ,则表示 t1 树和t2 树的拓扑结构完全相同。

代码:
import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root1 TreeNode类 
     * @param root2 TreeNode类 
     * @return bool布尔型
     */
    public boolean isContains (TreeNode root1, TreeNode root2) {
        // write code here
        String res1=serialByPre(root1);
        String res2=serialByPre(root2);
        char[] s1=res1.toCharArray();
        char[] s2=res2.toCharArray();
        int j=0;
        int i=0;
        while(i<s1.length){
            if(j==(s2.length-1)&&s2[j]==s1[i]){
                return true;
            }
            if(s2[j]==s1[i]){
                i++;
                j++;
            }
            if(s2[j]!=s1[i]){
                i++;
                j=0;
            }
        }
        return false;
        
    }
    public String serialByPre(TreeNode root){
        if(root==null){
            return "#!";
        }
        String res=root.val+"!";
        res+=serialByPre(root.left);
        res+=serialByPre(root.right);
        return res;
    }
}

8.合并二叉树

题目描述:

已知两颗二叉树,将它们合并成一颗二叉树。合并规则是:都存在的结点,就将结点值加起来,否则空的位置就由另一个树的结点来代替。

代码:
import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param t1 TreeNode类 
     * @param t2 TreeNode类 
     * @return TreeNode类
     */
    public TreeNode mergeTrees (TreeNode t1, TreeNode t2) {
        // write code here
        t1.val=t1.val+t2.val;
        if(t1.left!=null&&t2.left!=null){
            mergeTrees(t1.left,t2.left);
        }
        else if(t1.left==null&&t2.left!=null){
            t1.left=t2.left;
        }
        if(t1.right!=null&&t2.right!=null){
            mergeTrees(t1.right,t2.right);
        }
        else if(t1.right==null&&t2.right!=null){
            t1.right=t2.right;
        }
        return t1;
    }
}

9.找到搜索二叉树中两个错误的节点

题目描述:

一棵二叉树原本是搜索二叉树,但是其中有两个节点调换了位置,使得这棵二叉树不再是搜索二叉树,请按升序输出这两个错误节点的值。(每个节点的值各不相同)

代码:
import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 the root
     * @return int整型一维数组
     */
    List<Integer> arr=new ArrayList();
    public int[] findError (TreeNode root) {
        // write code here
        Inorder(root);
        int[] num=new int[2];
        int i;
        for(i=0;i<arr.size()-1;i++){
            if(arr.get(i)>arr.get(i+1)){
                num[1]=arr.get(i);
                break;
            }
        }
        for(int j=arr.size()-1;j>i;j--){
            if(arr.get(j)<arr.get(j-1)){
                num[0]=arr.get(j);
                break;
            }
        }
        return num;
    }
    
    public void Inorder(TreeNode root){
        if(root==null){
            return;
        }
        Inorder(root.left);
        arr.add(root.val);
        Inorder(root.right);
    }
}

10.将升序数组转化为平衡二叉搜索树

题目描述:

给出一个升序排序的数组,将其转化为平衡二叉搜索树(BST).

代码:
import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param num int整型一维数组 
     * @return TreeNode类
     */
    public TreeNode sortedArrayToBST(int[] num){
        if(num==null){
            return null;
        }
        return avl(num,0,num.length-1);
    }
    public TreeNode avl(int[] num,int left,int right){
        if(left>right){
            return null;
        }
        int mid=left+(right-left+1)/2;
        TreeNode root=new TreeNode(num[mid]);
        root.left=avl(num,left,mid-1);
        root.right=avl(num,mid+1,right);

        return root;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值