【剑指offer】二叉树刷题

二叉树遍历

先序遍历
class Solution {
    public List<Integer> preOrderRecursively(TreeNode root){
        List<Integer> res = new ArrayList<>();
        if(root == null){
            return res;
        }
        res.add(root.val);
        preOrderRecursively(root.left);
        preOrderRecursively(root.right);
        return res;
    }

    public List<Integer> preOrderIteratively(TreeNode tree){
        List<Integer> res = new ArrayList<>();
        if(root == null){
            return res;
        }
        TreeNode root = tree;
        Stack<TreeNode> stack = new Stack<>();
        while(root != null || !stack.isEmpty()){
            if(root != null){
                res.add(root.val);
                stack.push(root);
                root = root.left;
            }else{
                root = stack.pop().right;
            }
        }
        return res;
    }
}

中序遍历
    public List<Integer> inOrderRecursively(TreeNode root){
        List<Integer> res = new ArrayList<>();
        if(root == null){
            return res;
        }
        preOrderRecursively(root.left);
        res.add(root.val);
        preOrderRecursively(root.right);
        return res;
    }

    public List<Integer> inOrderIteratively(TreeNode tree){
        List<Integer> res = new ArrayList<>();
        if(root == null){
            return res;
        }
        TreeNode root = tree;
        Stack<TreeNode> stack = new Stack<>();
        while(root != null || !stack.isEmpty()){
            if(root != null){
                stack.push(root);
                root = root.left;
            }else{
                res.add(root.peek());
                root = stack.pop().right;
            }
        }
        return res;
    }
}

后序遍历
class Solution {
    public List<Integer> postOrderRecursively(TreeNode root){
        List<Integer> res = new ArrayList<>();
        if(root == null){
            return res;
        }
        preOrderRecursively(root.left);
        preOrderRecursively(root.right);
        res.add(root.val);
        return res;
    }

    public List<Integer> postOrderIteratively(TreeNode tree){
        List<Integer> res = new ArrayList<>();
        if(root == null){
            return res;
        }
        TreeNode root = tree;
        TreeNode prevVisted = null;
        Stack<TreeNode> stack = new Stack<>();
        while(root != null || !stack.isEmpty()){
            if(root != null){
                stack.push(root);
                root = root.left;
            }else{
                root = stack.peek().right;
                if(root != null && root != prevVisted){
                    stack.push(root);
                    root = root.left;
                }else{
                    prevVisted = stack.pop();
                    res.add(prevVisted.val);
                    root = null;
                }
            }
        }
        return res;
    }
}

层序遍历
class Solution {
    public List<Integer> levelOrder1(TreeNode tree) {
        List<Integer> res = new ArrayList<>();
        if(tree == null){
            return res;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(tree);
        TreeNode temp = null;
        while (!queue.isEmpty()) {
            temp = queue.poll();
            res.add(temp.val);
            if (temp.left != null) {
                queue.offer(temp.left);
            }
            if (temp.right != null) {
                queue.offer(temp.right);
            }
        }
        return res;
    }

    public List<Integer> levelOrder2(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if(tree == null){
            return res;
        }
        Queue queue = new LinkedList();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = size - 1; i >= 0; i--) {
                TreeNode temp = (TreeNode) queue.poll();
                res.add(temp.val);
                if (temp.left != null) {
                    queue.offer(temp.left);
                }
                if (temp.right != null) {
                    queue.offer(temp.right);
                }
            }
            return res;
        }
    }
}

JZ55 二叉树的深度

输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度,根节点的深度视为 1 。

输入:{1,2,3,4,5,#,6,#,#,7}

输出:4

1、递归
public class Solution {
    public int TreeDepth(TreeNode root) {
        if(root == null){
            return 0;
        }
        int left = TreeDepth(root.left);
        int right = TreeDepth(root.right);
        return Math.max(left , right) + 1;
    }
}

2、层序遍历
public class Solution {
    public int TreeDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int depth = 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            depth++;
        }
        return depth;
    }
}

JZ79 判断是不是平衡二叉树

输入一棵节点数为 n 二叉树,判断该二叉树是否是平衡二叉树。

输入:{1,2,3,4,5,6,7}

输出:true

class Solution {
    public boolean isBalanced(TreeNode root) {
        if(deep(root) == -1){
            return false;
        }
        return true;
    }

    public int deep(TreeNode root){
        if(root == null){
            return 0;
        }
        int left = deep(root.left);
        if(left == -1){
            return -1;
        }
        int right = deep(root.right);
        if(right == -1){
            return -1;
        }
        if(Math.abs(left - right) > 1){
            return -1;
        }
        return left > right? left+1 : right+1;
    }
}

JZ27 二叉树的镜像

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

输入:{8,6,10,5,7,9,11}

输出:{8,10,6,11,9,7,5}

class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        if(root == null){
            return null;
        }
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        mirrorTree(root.left);
        mirrorTree(root.right);
        return root;
    }
}
// 层次遍历
class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        if(root == null){
            return null;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        TreeNode node = null;
        queue.add(root);
        while(!queue.isEmpty()){
            node = queue.poll();
            if(node.left != null){
                queue.add(node.left);
            }
            if(node.right != null){
                queue.add(node.right);
            }
            TreeNode tmp = node.left;
            node.left = node.right;
            node.right = tmp;
        }

        return root;
    }
}

JZ28 对称的二叉树

请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。

输入:{1,2,2,3,4,4,3}

输出:true

class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root == null){
            return true;
        }
        return isEqual(root.left, root.right);
    }

    public boolean isEqual(TreeNode left, TreeNode right){
        if(left == null && right == null){
            return true;
        }
        if(left == null || right == null){
            return false;
        }
        if(left.val == right.val){
            return isEqual(left.left, right.right) && isEqual(left.right, right.left);
        }else{
            return false;
        }
    }
}

JZ26 树的子结构

输入两棵二叉树A,B,判断B是不是A的子结构。(我们约定空树不是任意一个树的子结构)

输入:{8,8,7,9,2,#,#,#,#,4,7},{8,9,2}

输出:true

class Solution {
    public boolean isSubStructure(TreeNode A, TreeNode B) {
        if(A == null || B == null){
            return false;
        }
    return isSubStructure(A.left, B) || isSubStructure(A.right, B) || hasSubTree(A, B);
        

    }
    public boolean hasSubTree(TreeNode A, TreeNode B){
        if(B == null){
            return true;
        }
        if(A == null){
            return false;
        }
        if(A.val == B.val){
            return hasSubTree(A.left, B.left) && hasSubTree(A.right, B.right);
        }else{
            return false;
        }
    }
}

JZ32 从上往下打印二叉树 Ⅰ

不分行从上往下打印出二叉树的每个节点,同层节点从左至右打印。

输入:{8,6,10,#,#,2,1}

输出:[8,6,10,2,1]

class Solution {
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
        ArrayList<Integer> res = new ArrayList<>();
        if(root == null){
            return res;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            TreeNode node = queue.poll();
            if(node.left != null){
                queue.offer(node.left);
            }
            if(node.right != null){
                queue.offer(node.right);
            }
            res.add(node.val);
        }
        return res;
    }
}

JZ78 从上往下打印二叉树 Ⅱ

从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。

输入:{8,6,10,#,#,2,1}

输出:[[8],[6,10],[2,1]]

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if (root == null) {
            return res;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                list.add(node.val);
            }
            res.add(list);
        }
        return res;
    }
}

JZ77 从上往下打印二叉树 Ⅲ

请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。

输入:{1,2,3,#,#,4,5}

输出:[[1],[3,2],[4,5]]

说明:如题面解释,第一层是根节点,从左到右打印结果,第二层从右到左,第三层从左到右。

public class Solution {
    public ArrayList<ArrayList<Integer>> Print (TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
        if (pRoot == null) {
            return res;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(pRoot);
        boolean flag = false;
        while (!queue.isEmpty()) {
            int size = queue.size();
            ArrayList<Integer> list = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                if(flag){
                    list.add(0, node.val);
                }else{
                    list.add(node.val);
                }
            }
            res.add(list);
            flag = !flag;
        }
        return res;
    }
}

JZ7 重建二叉树

给定节点数为 n 的二叉树的前序遍历和中序遍历结果,请重建出该二叉树并返回它的头结点。

输入:[1,2,4,7,3,5,6,8],[4,7,2,1,5,3,8,6]

输出:{1,2,3,4,#,5,6,#,7,#,#,8}

class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if(preorder.length == 0 || inorder.length == 0){
            return null;
        }
        TreeNode root = new TreeNode(preorder[0]);
        int len = preorder.length;
        for(int i=0; i<len; i++){
            if(inorder[i] == preorder[0]){
                root.left = buildTree(Arrays.copyOfRange(preorder, 1, i+1), Arrays.copyOfRange(inorder, 0, i));
                root.right = buildTree(Arrays.copyOfRange(preorder, i+1, len), Arrays.copyOfRange(inorder, i+1, len));
            }
        }
        return root;
    }
}

JZ33 二叉搜索树的后序遍历序列

输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则返回 true ,否则返回 false 。假设输入的数组的任意两个数字都互不相同。

输入:[1,3,2]

输出:true

public class Solution {
    public boolean VerifySquenceOfBST(int [] sequence) {
        if(sequence.length == 0){
            return false;
        }
        return verify(sequence);
    }

    public boolean verify(int[] sequence){
        int len = sequence.length;
        if(len == 0){
            return true;
        }
        int root = sequence[len-1];
        int index = 0;
        while(index < len-1){
            if(sequence[index] > root){
                break;
            }
            index++;
        }
        int temp = index;
        while(temp < len-1){
            if(sequence[temp] < root){
                return false;
            }
            temp++;
        }
        return verify(Arrays.copyOfRange(sequence, 0, index)) && verify(Arrays.copyOfRange(sequence, index, len-1));
    }
}

JZ54 二叉搜索树的第k个节点

给定一棵二叉搜索树,请找出其中第 k 大的节点的值。

输入:root = [3,1,4,null,2], k = 1

输出:4

class Solution {
    public int kthLargest(TreeNode proot, int k) {
        if(proot == null){
            return -1;
        }
        Stack<TreeNode> stack = new Stack<>();
        while(proot != null || !stack.isEmpty()){
            if(proot != null){
                stack.push(proot);
                proot = proot.right;
            }else{
                if(--k == 0){
                    return stack.peek().val;
                }
                proot = stack.pop().left;
            }
        }
        return -1;
    }

JZ68 二叉搜索树的最近公共祖先

给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。

输入:root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8

输出:6

1、递归
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(p.val < root.val && q.val < root.val){
            return lowestCommonAncestor(root.left, p, q);
        }else if(p.val > root.val && q.val > root.val){
            return lowestCommonAncestor(root.right, p, q);
        }else{
            return root;
        }
    }
}
2、非递归
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        while(root != null){
            if(root.val < p.val && root.val < q.val){
                root = root.right;
            }else if(root.val > p.val && root.val > q.val){
                root = root.left;
            }else{
                break;
            }
        }
        return root;
    }
}

JZ37 序列化二叉树

给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。

输入:{1,2,3,#,#,6,7}

输出:{1,2,3,#,#,6,7}

public class Solution {
    String Serialize(TreeNode root) {
        if (root == null) {
            return "[]";
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        StringBuilder res = new StringBuilder("[");
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            if (node != null) {
                res.append(node.val + ",");
                queue.offer(node.left);
                queue.offer(node.right);
            } else {
                res.append("null,");
            }
        }
        res.deleteCharAt(res.length()-1);
        res.append("]");
        return res.toString();
    }
    TreeNode Deserialize(String str) {
        if (str.equals("[]")) {
            return null;
        }
        String[] arr = str.substring(1, str.length() - 1).split(",");
        Queue<TreeNode> queue = new LinkedList<>();
        TreeNode root = new TreeNode(Integer.parseInt(arr[0]));
        queue.offer(root);
        int index = 1;
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            if (!arr[index].equals("null")) {
                node.left = new TreeNode(Integer.parseInt(arr[index]));
                queue.offer(node.left);
            }
            index++;
            if (!arr[index].equals("null")) {
                node.right = new TreeNode(Integer.parseInt(arr[index]));
                queue.offer(node.right);
            }
            index++;
        }
        return root;
    }
}

补充1 二叉树的直径

给你一棵二叉树的根节点,返回该树的 直径 。二叉树的 直径 是指树中任意两个节点之间最长路径的 长度 。这条路径可能经过也可能不经过根节点 root 。两节点之间路径的 长度 由它们之间边数表示。

输入:root = [1,2,3,4,5]

输出:3

说明:3 ,取路径 [4,2,1,3] 或 [5,2,1,3] 的长度。

class Solution {
    int res = 0;
    public int diameterOfBinaryTree(TreeNode root) {
        dfs(root);
        return res;
    }

    public int dfs(TreeNode node){
        if(node == null){
            return 0;
        }
        int left = dfs(node.left);
        int right = dfs(node.right);
        res = Math.max(left + right, res);
        return Math.max(left, right) + 1;
    }
}

补充2 二叉树的右视图

给定一个二叉树的 根节点 root,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。

输入:[1,2,3,null,5,null,4]

输出:[1,3,4]

1、层序遍历
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if(root == null){
            return res;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            for(int i=0; i<size; i++){
                TreeNode node = queue.poll();
                if(node.left != null){
                    queue.offer(node.left);
                }
                if(node.right != null){
                    queue.offer(node.right);
                }
                if(i == size-1){
                    res.add(node.val);
                }
            }
        }
        return res;
    }
}
2、深度优先
class Solution {
    List<Integer> res = new ArrayList<>();
    public List<Integer> rightSideView(TreeNode root) {
        dfs(root, 0);
        return res;
    }
    public void dfs(TreeNode root, int depth){
        if(root == null){
            return;
        }
        if(depth == res.size()){
            res.add(root.val);
        }
        depth++;
        dfs(root.right, depth);
        dfs(root.left, depth);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值