【数据结构】二叉树面试题

目录

1.二叉树的最大深度

2.相同的树

3.另一棵树的子树

4.翻转二叉树

5.平衡二叉树

6.对称二叉树

7.完全二叉树

8.二叉树遍历

9.层序遍历

10.根据中序和前序序列构造二叉树

11.根据中序和后序序列构造二叉树

12.二叉树的最近公共祖先

13.非递归前序遍历

14.非递归中序遍历

15.非递归后序遍历

16.二叉树创建字符串 

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;
    }
 }

1.二叉树的最大深度

二叉树的最大深度

class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftH = maxDepth(root.left);
        int rightH = maxDepth(root.right);
        return (leftH > rightH ? leftH: rightH) + 1;
    }
}

2.相同的树

相同的树

时间复杂度O(min(m, n)),其中m,n为两棵树的结点个数。

class Solution {
    public boolean isSameTree(TreeNode p, TreeNode 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);
    }
}

3.另一棵树的子树

另一棵树的子树

时间复杂度O( |s|x|t| ),其中s为主树结点数,t为子树结点数。

class Solution {
    public boolean isSameTree(TreeNode p, TreeNode 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(TreeNode root, TreeNode subRoot) {
        if (root == null) {
            return false;
        }
        if (isSameTree(root,subRoot)) {
            return true;
        }
        if (isSubtree(root.left,subRoot)) {
            return true;
        }
        if (isSubtree(root.right,subRoot)) {
            return true;
        }
        return false;
    }
}

4.翻转二叉树

翻转二叉树

class Solution {
    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        TreeNode tmp = null;
        tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }
}

5.平衡二叉树

平衡二叉树

法一:

class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftH = maxDepth(root.left);
        int rightH = maxDepth(root.right);
        return (leftH > rightH ? leftH: rightH) + 1;
    }
    //时间复杂度 O(n^2)
    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        int leftHeight = maxDepth(root.left);
        int rightHeight = maxDepth(root.right);
        return Math.abs(leftHeight-rightHeight) < 2
        && isBalanced(root.left)
        && isBalanced(root.right);
    }
}

法二:

class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftH = maxDepth(root.left);
        int rightH = maxDepth(root.right);
        if (leftH >= 0 && rightH >=0 
        && Math.abs(leftH-rightH) <= 1) {
            return Math.max(leftH,rightH) + 1;
        }else {
            return -1;
        }
    }
    //时间复杂度 O(n)
    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        return maxDepth(root) >= 0;
    }
}

6.对称二叉树

对称二叉树

class Solution {
    public boolean isSymmetricChild(TreeNode leftTree,TreeNode rightTree) {
        if (leftTree == null && rightTree != null 
         || leftTree != null && rightTree == null) {
            return false;
        }
        if (leftTree == null && rightTree == null) {
            return true;
        }
        if (leftTree.val != rightTree.val) {
            return false;
        }

        return isSymmetricChild(leftTree.left,rightTree.right)
        && isSymmetricChild(leftTree.right,rightTree.left);
    }
    public boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return true;
        }
        return isSymmetricChild(root.left,root.right);
    }
}

7.完全二叉树

判断是否为完全二叉树,没有找到链接o.O

class Solution {
    public boolean isCompleteTree(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        if (root != null) {
            queue.offer(root);
        }
        while (!queue.isEmpty()) {
            TreeNode top = queue.poll();
            if (top != null) {
                queue.offer(top.left);
                queue.offer(top.right);
            }else {
                break;
            }
        }
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if (cur != null) {
                return false;
            }
        }
        return true;
    }
}

8.二叉树遍历

二叉树遍历

注意这题 TreeNode 中的 val 要改为char类型。

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextLine()) { 
            String str = in.nextLine();
            TreeNode root = createTree(str);
            inOrder(root);
        }
    }
    
    public static int i = 0;
    public static TreeNode createTree(String str) {
        TreeNode root = null;
        if (str.charAt(i) != '#') {
            root = new TreeNode(str.charAt(i));
            i++;

            root.left = createTree(str);
            root.right = createTree(str);
        }else {
            i++;
        }
        return root;
    }
    public static void inOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        inOrder(root.left);
        System.out.print(root.val+" ");
        inOrder(root.right);
    }
}

9.层序遍历

层序遍历

class Solution {
    //层序遍历:利用队列
    //法一:有返回值    
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<>();
        if (root == null) {
            return ret;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> list = new ArrayList<>();
            while (size != 0) {
                TreeNode top = queue.poll();
                list.add(top.val);
                if (top.left != null) {
                    queue.offer(top.left);
                }
                if (top.right != null) {
                    queue.offer(top.right);
                }
                size--;
            }
            ret.add(list);
        }
        return ret;
    }
    //法二:无返回值
    public void levelOrder2(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        if (root != null) {
            queue.offer(root);
        }
        while (!queue.isEmpty()) {
            TreeNode top = queue.poll();
            System.out.print(top.val + " ");
            if (top.left != null) {
                queue.offer(top.left);
            }
            if (top.right != null) {
                queue.offer(top.right);
            }
        }
    }
}

10.根据中序和前序序列构造二叉树

根据中序和前序序列构造二叉树

class Solution {
    public int preIndex = 0;

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTreeChild(preorder, inorder, 0, inorder.length-1);
    }

    private TreeNode buildTreeChild(int[] preorder,int[] inorder,int inbegin,int inend) {
        //递归的出口,不满足条件说明没有左树或右树
        if (inbegin > inend) {
            return null;
        }
        
        //创建根结点
        TreeNode root = new TreeNode(preorder[preIndex]);
        
        //在中序序列中找到根结点所在的位置
        int rootIndex = findIndex(inorder,inbegin,inend,preorder[preIndex]);

        preIndex++;

        //创建左右树
        root.left = buildTreeChild(preorder,inorder,inbegin,rootIndex-1);
        root.right = buildTreeChild(preorder,inorder,rootIndex+1,inend);

        return root;
    }
    //在中序序列中找到根结点所在的位置
    private int findIndex(int[] inorder, int inbegin, int inend, int key) {
        for (int i = inbegin; i <= inend ; i++) {
            if (inorder[i] == key) {
                return i;
            }
        }
        return -1;
    }
}

11.根据中序和后序序列构造二叉树

根据中序和后序序列构造二叉树

class Solution {
    public int postIndex = 0;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        postIndex = postorder.length-1;
        return buildTreeChild(postorder, inorder, 0, inorder.length-1);
    }
    private TreeNode buildTreeChild(int[] postorder,int[] inorder,int inbegin,int inend) {
        //递归的出口,不满足条件说明没有左树或右树
        if (inbegin > inend) {
            return null;
        }

        //创建根结点
        TreeNode root = new TreeNode(postorder[postIndex]);

        //在中序序列中找到根结点所在的位置
        int rootIndex = findIndex(inorder,inbegin,inend,postorder[postIndex]);

        postIndex--;

        //创建右左树
        root.right = buildTreeChild(postorder,inorder,rootIndex+1,inend);
        root.left = buildTreeChild(postorder,inorder,inbegin,rootIndex-1);
       

        return root;
    }
    //在中序序列中找到根结点所在的位置
    private int findIndex(int[] inorder, int inbegin, int inend, int key) {
        for (int i = inbegin; i <= inend ; i++) {
            if (inorder[i] == key) {
                return i;
            }
        }
        return -1;
    }
}

12.二叉树的最近公共祖先

二叉树的最近公共祖先

法一:搜索二叉树

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return null;
        }
        if (p == root || q == root) {
            return root;
        }
        
        TreeNode leftRet = lowestCommonAncestor(root.left,p,q);
        TreeNode rightRet = lowestCommonAncestor(root.right,p,q);
        
        if (leftRet != null && rightRet != null) {
            return root;
        }else if (leftRet != null) {
            return leftRet;
        }else {
            return rightRet;
        }
    }
}

法二:链表相交+栈

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return null;
        }
        Stack<TreeNode> s1 = new Stack<>();
        getPath(root,p,s1);

        Stack<TreeNode> s2 = new Stack<>();
        getPath(root,q,s2);

        int size1 = s1.size();
        int size2 = s2.size();

        if (size1 > size2) {
            int size = size1 - size2;
            while (size != 0) {
                s1.pop();
                size--;
            }
        }else {
            int size = size2 - size1;
            while (size != 0) {
                s2.pop();
                size--;
            }
        }
        while (!s1.empty() && !s2.empty()) {
            TreeNode tmp1 = s1.pop();
            TreeNode tmp2 = s2.pop();
            if (tmp1 == tmp2) {
                return tmp1;
            }
        }
        return null;
    }

    //获取root这棵树下node所在结点的路径
    public boolean getPath(TreeNode root, TreeNode node, Stack<TreeNode> stack) {
        if (root == null) {
            return false;
        }
        stack.push(root);
        if (root == node) {
            return true;
        }
        boolean ret = getPath(root.left,node,stack);
        if (ret == true) {
            return true;
        }
        boolean ret2 = getPath(root.right,node,stack);
        if (ret2 == true) {
            return true;
        }
        stack.pop();
        return false;
    }
}
}

13.非递归前序遍历

非递归前序遍历

class Solution {
    public void preOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;

        while (cur != null || !stack.empty()) {
            while (cur != null) {
                stack.push(cur);
                System.out.print(cur.val+" ");
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            cur = top.right;
        }
    }
}

14.非递归中序遍历

非递归中序遍历

class Solution {
    public void inOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;

        while (cur != null || !stack.empty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            System.out.print(cur.val+" ");
            cur = top.right;
        }
    }
}

15.非递归后序遍历

非递归后序遍历

class Solution {
    public void postOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode prev = null;

        while (cur != null || !stack.empty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.peek();

            if (top.right == null || top.right == prev) {
                System.out.println(top.val+" ");
                prev = top;
                stack.pop();
            }else {
                cur = top.right;
            }
        }
    }
}

16.二叉树创建字符串

二叉树创建字符串

class Solution {
    public String tree2str(TreeNode root) {
        StringBuilder stringBuilder = new StringBuilder();
        tree2strChild(root,stringBuilder);
        return stringBuilder.toString();
    }
    public void tree2strChild(TreeNode root,StringBuilder stringBuilder) {
        if (root == null) {
            return;
        }
        stringBuilder.append(root.val);

        if (root.left != null) {
            stringBuilder.append("(");
            tree2strChild(root.left,stringBuilder);
            stringBuilder.append(")");
        }else {
            if (root.right == null) {
                return;
            }else {
                stringBuilder.append("()");
            }
        }

        if (root.right != null) {
            stringBuilder.append("(");
            tree2strChild(root.right,stringBuilder);
            stringBuilder.append(")");
        }else {
            return;
        }
    }
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值