树练习题02

99. 恢复二叉搜索树

题目

在这里插入图片描述

代码

/**
 * Definition for a binary tree node.
 * 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;
 *     }
 * }
 */
class Solution {
    private TreeNode x=null;
    private TreeNode y=null;
    private TreeNode pre=null;
    public void recoverTree(TreeNode root) {
        dfs(root);
        // 对于遍历得到的两个倒序节点进行交换
        if(x!=null&&y!=null){
            int tmp=x.val;
            x.val=y.val;
            y.val=tmp;
        }
    }
    // 中序遍历节点,得到错位的两个节点x,y
    void dfs(TreeNode root){
        if(root==null) return;
        dfs(root.left);
        // 对于未对pre赋值时,直接将root赋值给pre(第一次中序遍历到bst最小值)
        if(pre==null){
            pre=root;
        }else{
            // 对于后续的节点依次比较pre与当前root节点值大小,使用x记录到第一个错位pre,y记录最后一个错位的节点
            if(pre.val>root.val){
                y=root;
                if(x==null){
                    x=pre;
                }
            }
            // 把pre替换为当前遍历的节点
            pre=root;
        }
        dfs(root.right);
    }
}
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:

    def recoverTree(self, root: TreeNode) -> None:
        """
        Do not return anything, modify root in-place instead.
        """
        self.pre=None
        self.x=None
        self.y=None
        def dfs(root):
            if not root:return 
            dfs(root.left)
            if not self.pre:
                self.pre=root
            else:
                if self.pre.val>root.val:
                    self.y=root
                    if not self.x:
                        self.x=self.pre
                self.pre=root
            dfs(root.right)
        dfs(root)
        if  self.x and  self.y:
            self.x.val,self.y.val=self.y.val,self.x.val

102. 二叉树的层序遍历

题目

在这里插入图片描述

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
//  迭代实现层序遍历二叉树
// import java.util.*;
// class Solution {
//     public List<List<Integer>> levelOrder(TreeNode root) {
//         if(root==null) {
//             return new ArrayList<List<Integer>>();
//         }
//         List<List<Integer>> res=new ArrayList<List<Integer>>();
//         LinkedList<TreeNode> queue=new LinkedList<TreeNode>();
//         queue.add(root);
//         while(queue.size()>0){
//             // 注意队列中的元素个数相当于本层的节点个数
//             int size=queue.size();
//             // 设置一个临时列表存储每一层的节点
//             List<Integer> tmp=new ArrayList<>();
//             // 从队列中取出本层所有节点,并将其装入tmp临时列表中,同时将节点的子节点按从左到右依次存入队列中
//             for(int i=0;i<size;++i){
//                 TreeNode node=queue.remove();
//                 tmp.add(node.val);
//                 if(node.left!=null) queue.add(node.left);
//                 if(node.right!=null) queue.add(node.right);
//             }
//             res.add(tmp);
//         }
//         return res;
//     }
// }
// 递归遍历二叉树
import java.util.*;
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        //对于空的二叉树直接返回一个空的list
        if(root==null) return new ArrayList<List<Integer>>();
        // 构建一个存放结果的二维列表
        List<List<Integer>> res=new ArrayList<List<Integer>>();
        dfs(1,root,res);
        return res;  
    }
    void dfs(int n,TreeNode root,List<List<Integer>> res){
        // 对于res中第一次添加该层的节点时,在新建一个该层的列表,并将其添加进res二维列表中去
        if(res.size()<n){
            res.add(new ArrayList<Integer>());
        }
        res.get(n-1).add(root.val);
        // 开始递归左子树
        if(root.left!=null){
            dfs(n+1,root.left,res);
        }
        if(root.right!=null)
            dfs(n+1,root.right,res);
    }
}
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
# 迭代法1
# class Solution:
#     def levelOrder(self, root: TreeNode) -> List[List[int]]:
#         if not root: return []
#         queue=[root]
#         res=[]
#         while queue :
#             tmp=[]
#             for _ in range(len(queue)):
#                 r=queue.pop(0)
#                 tmp.append(r.val)
#                 if r.left:
#                     queue.append(r.left)
#                 if r.right:
#                     queue.append(r.right)
#             res.append(tmp)
#         return res
# 递归方法2
# class Solution(object):
# 	def levelOrder(self, root: TreeNode) -> List[List[int]]:
#         def dfs(n,root,res):
#             if len(res)<n:
#                 res.append([])
#             res[n-1].append(root.val)
#             if root.left:
#                 dfs(n+1,root.left,res)
#             if root.right:
#                 dfs(n+1,root.right,res)
#         if not root:
#             return []
#         res=[]
#         dfs(1,root,res)
#         return res

103. 二叉树的锯齿形层次遍历

题目

在这里插入图片描述

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.*;
// 使用迭代方法
class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        // 对于空的字符串直接返回空
        if(root==null) return new ArrayList<List<Integer>>();
        List<List<Integer>> res=new ArrayList<List<Integer>>();
        LinkedList<TreeNode> queue=new LinkedList<>();
        queue.add(root);
        boolean flag=true;
        while(queue.size()>0){
            LinkedList<Integer> tmp=new LinkedList<>();
            int size=queue.size();
            for(int i=0;i<size;i++){
                TreeNode node=queue.pop();
                // 当flag为true时由左到右进行存储
                if(flag==true){   
                    tmp.add(node.val);
                }else{
                    tmp.addFirst(node.val);
                }
                if(node.left!=null) queue.add(node.left);
                if(node.right!=null) queue.add(node.right);

            }
            res.add(tmp);
            flag=!flag;
        }
        return res;
    }
}
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
        # 使用迭代法
        if not root: return []
        res=[]
        queue=[root]
        flag=True
        while queue:
            size=len(queue)
            tmp=[]
            for _ in range(size):
                node=queue.pop(0)
                tmp.append(node.val)
                if node.left: queue.append(node.left)
                if node.right:queue.append(node.right)
            if not flag:
                tmp=tmp[::-1]
            flag=not flag
            res.append(tmp)
        return res

106. 从中序与后序遍历序列构造二叉树(剑指offer07重构二叉树)

题目

在这里插入图片描述

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
//  根据剑指offer07重建二叉树,先序遍历+中序遍历思路相同

class Solution {
    HashMap<Integer,Integer> map=new HashMap<>();
    int[] post;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        post=postorder;
        // 将中序遍历的节点值与index储存起来,便于查找
        for(int i=0;i<inorder.length;i++){
            map.put(inorder[i],i);
        }
        return recur(postorder.length-1,0,inorder.length-1);
    }
    TreeNode recur(int pos_root,int in_left,int in_right){
        if(in_left>in_right) return null;
        TreeNode node=new TreeNode(post[pos_root]);
        // 取出pos_root在中序遍历中的index
        int i=map.get(post[pos_root]);
        node.right=recur(pos_root-1,i+1,in_right);
        node.left=recur(pos_root-in_right+i-1,in_left,i-1);
        return node;
    }
}
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
        # 添加两个全局变量,使用字典存储中序遍历的节点值与数组中的index,post为全局变量便于根据index查找节点值
        self.dic,self.post={},postorder
        for i in range(len(inorder)):
            self.dic[inorder[i]]=i
        return self.recur(len(postorder)-1, 0, len(inorder)-1)
    def recur(self,pos_root,in_left,in_right):
        if in_left>in_right: return None
        # 构建当前节点
        node=TreeNode(self.post[pos_root])
        # 获取当前节点在后序遍历数组中的index
        i=self.dic[self.post[pos_root]]
        node.right=self.recur(pos_root-1,i+1,in_right)
        node.left=self.recur(pos_root-in_right+i-1,in_left,i-1)
        return node
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值