二叉树问题

本文详细介绍了二叉树的各种遍历方法,包括前序、中序、后序遍历的递归与迭代实现,以及层序遍历(广度优先搜索)。此外,还涵盖了二叉树的最大深度计算、对称性检查、翻转、路径总和判断、二叉搜索树验证及构造二叉树等算法。这些内容对于理解二叉树操作至关重要。
摘要由CSDN通过智能技术生成

1、二叉树的前序遍历

在这里插入图片描述
前序遍历的输入顺序为:A-B-D-F-G-H-I-E-C

递归法
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<Integer>();
        pre(root,list);
        return list;
    }
    //前序遍历
    void pre(TreeNode root,List<Integer> list){
    	//当节点为空时,返回
        if(root == null){
            return;
        }
        list.add(root.val);		//先用list记录当前节点值
        pre(root.left,list);	//递归遍历节点的左子树
        pre(root.right,list);	//递归遍历节点的右子树
    }
}
迭代法
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        if (root == null) {
            return res;
        }
		
		//Deque是双端队列,可以在两端插入删除元素
        Deque<TreeNode> stack = new LinkedList<TreeNode>();
        TreeNode node = root;
        while (!stack.isEmpty() || node != null) {
            while (node != null) {
                res.add(node.val);	//添加该节点值
                stack.push(node);	//将该节点压入队列中
                node = node.left;	//如果node.left存在,则重复第二个while循环
            }
            node = stack.pop();	//最近压入队列中的节点出队列
            node = node.right;
        }
        return res;
    }
}

2、二叉树的中序遍历

在这里插入图片描述
中序遍历的输入顺序为:F-D-H-G-I-B-E-A-C

递归法
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<Integer>();
        mid(root,list);
        return list;
    }
    void mid(TreeNode root,List<Integer> list){
        if(root == null){
            return;
        }
        mid(root.left,list);	//直接递归到最左节点
        list.add(root.val);		//添加该节点的值
        mid(root.right,list);	//再递归右子树
    }
}
迭代法
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        Deque<TreeNode> stk = new LinkedList<TreeNode>();
        while (root != null || !stk.isEmpty()) {
            while (root != null) {	//当压入到最左节点时停止
                stk.push(root);		//不断压入
                root = root.left;
            }
            root = stk.pop();	//通过出队列,节点不断往上走
            res.add(root.val);
            root = root.right;
        }
        return res;
    }
}

3、二叉树的后序遍历

在这里插入图片描述
后序遍历的输入顺序为:F-H-I-G-D-E-B-C-A

递归法
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<Integer>();
        mid(root,list);
        return list;
    }
    void mid(TreeNode root,List<Integer> list){
        if(root == null){
            return;
        }
        mid(root.left,list);	//直接递归到最左节点
        mid(root.right,list);	//再看右子树
        list.add(root.val);		//最后添加该节点的值
    }
}

4、二叉树的层序遍历

在这里插入图片描述

层序遍历
输入:root = [3,9,20,null,null,15,7]
输出:[[3],[9,20],[15,7]]

广度优先搜索BFS
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> list1= new ArrayList<List<Integer>>();
        if(root == null){
            return list1;
        }
        //BFS
        Queue<TreeNode> queue = new LinkedList<TreeNode>();	//单端队列,先进先出
        queue.add(root);
        while(!queue.isEmpty()){
            List<Integer> list2= new ArrayList<Integer>();
            int size = queue.size();	//size为当前队列的长度
            for(int i=1;i<=size;i++){
                TreeNode node = queue.poll(); //将一个节点出队列
                list2.add(node.val);	//添加该节点的值
                if(node.left != null){	//如果有左子树,左子树进队列
                    queue.add(node.left);
                }
                if(node.right != null){	//如果有右子树,右子树进队列
                    queue.add(node.right);
                }
            }
            //在一个for循环后,这同一层的节点值都在lsit2中了
            list1.add(list2);
        }
        return list1;
    }
}

5、二叉树的最大深度问题

在这里插入图片描述

最大深度为:3

递归法:深度优先搜索DFS

在这里插入图片描述

class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null){ //节点为空,返回0
            return 0;
        }
        else{
            int leftmax = maxDepth(root.left);	//遍历左子树
            int rightmax = maxDepth(root.right);
            return Math.max(leftmax,rightmax)+1;
        }

    }  
}
广度优先搜索
class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        int ans = 0;	//记录高度的计数器
        while (!queue.isEmpty()) {
            int size = queue.size();
            while (size > 0) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                size--;
            }
            ans++;	//每完成一次while循环,高度就加一
        }
        return ans;
    }
}

6、对称二叉树

在这里插入图片描述

递归法
class Solution {
    public boolean isSymmetric(TreeNode root) {
        return compare(root.left,root.right);
    }
    boolean compare(TreeNode left,TreeNode right){
    	//当左右节点不为空,且值相等时,比较判断左节点的左子树和右节点的右子树,左节点的右子树和右节点的左子树是否相等。
        if((left!=null&&right!=null)&&left.val==right.val){
            return compare(left.left,right.right) && compare(left.right,right.left);
        }
        //直至都为空时,判断完成,返回true
        else if(left==null && right==null){
            return true;
        }
        else{
            return false;
        }
    }
}

7、翻转二叉树

在这里插入图片描述

递归法
class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root == null){
            return null;
        }
        TreeNode left1 = invertTree(root.right);
        TreeNode right1 = invertTree(root.left);
        root.left = left1;
        root.right = right1;
        return root;
    }
}

8、二叉树的路径总和

在这里插入图片描述
判断二叉树根节点到叶子节点的路径总和是否为targetSum。如果是,返回true,否则返回false。

递归法
class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if(root == null){
            return false;
        }
        if(root.left == null && root.right ==null){
            return targetSum == root.val;
        }
        return hasPathSum(root.left,targetSum-root.val) || hasPathSum(root.right,targetSum-root.val);

    }
}

9、验证二叉搜索树

在这里插入图片描述

中序遍历法
class Solution {
    public boolean isValidBST(TreeNode root) {
        Deque<TreeNode> stack = new LinkedList<TreeNode>();
        double inorder = -Double.MAX_VALUE;

        while (!stack.isEmpty() || root != null) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
              // 如果中序遍历得到的节点的值小于等于前一个 inorder,说明不是二叉搜索树
            if (root.val <= inorder) {
                return false;
            }
            inorder = root.val;
            root = root.right;
        }
        return true;
    }
}
递归法
class Solution {
    public boolean isValidBST(TreeNode root) {
        return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }

    public boolean isValidBST(TreeNode node, long lower, long upper) {
        if (node == null) {
            return true;
        }
        if (node.val <= lower || node.val >= upper) {
            return false;
        }
        return isValidBST(node.left, lower, node.val) && isValidBST(node.right, node.val, upper);
    }
}

10、根据前序与中序遍历序列构造二叉树

在这里插入图片描述

class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if(preorder.length==0 || inorder.length==0){
            return null;
        }
        TreeNode root = new TreeNode(preorder[0]);
        for(int i=0;i<preorder.length;i++){
            if(preorder[0] == inorder[i]){
                // 前序遍历:根左右
                // 中序遍历:左根右
                root.left = buildTree(Arrays.copyOfRange(preorder,1,i+1),
                            Arrays.copyOfRange(inorder,0,i));
                root.right = buildTree(Arrays.copyOfRange(preorder,i+1,preorder.length),
                            Arrays.copyOfRange(inorder,i+1,inorder.length));
                break;
            }
        }
        return root;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值