java数据结构总结——二叉树经典习题

(一)检查两颗二叉树是否相同

public boolean isSameTree(Node p, Node q) {
        if( (p == null && q != null) || (p != null && q == null)) {
            return false;
        }
        if(p == null && q == null) {
            return true;
        }

        if(p.val != q.val) {
            return false;
        }

        return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
    }

(二)另一颗树的子树

public boolean isSubtree(Node s, Node t) {
        if(s == null || t == null) {
            return false;
        }
        if(isSameTree(s,t)) {
            return true;
        }
        if(isSubtree(s.left,t)) {
            return true;
        }
        return isSubtree(s.right,t);
    }

(三)判断一颗二叉树是否是平衡二叉树

public boolean isSymmetric(Node root) {
            if(root == null) {
                return true;
            }
           return Math.abs(maxDepth(root.right) - maxDepth(root.right)) <= 1 &&
                   isSymmetric(root.left) && isSymmetric(root.right);
        }
        
private int maxDepth(Node root) {
        if(root == null) {
            return 0;
        }
        return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
    }

(四)判断一颗二叉树是否是对称二叉树

private boolean isSymmctricChild(Node leftTree,Node rightTree) {
        if(leftTree != null && rightTree == null ||leftTree == null && rightTree != null) {
            return false;
        }
        if(leftTree == null && rightTree == null) {
            return true;
        }
        return leftTree.val == rightTree.val && isSymmctricChild(leftTree.left,rightTree.right) &&
                isSymmctricChild(leftTree.right,rightTree.left);
    }
	public boolean isSymmctric(Node root) {
		if(root == null) {
			return true;
		}
		return isSymmctricChild(root.left,root,right);
	}

(五)二叉树的分层遍历

public void levelOrderTraversal(Node root){

        if(root == null) {
            return;
        }
        Queue<Node> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()) {
            Node cur = queue.poll();
            if(cur != null) {
                System.out.print(cur.val+"");
                if(cur.left != null) {
                    queue.offer(cur.left);
                }
                if(cur.right != null) {
                    queue.offer(cur.right);
                }
            }
        }
        System.out.println();

    }

你可能感兴趣的:(java数据结构总结——二叉树经典习题)