leetcode必刷高频题--树

119 阅读5分钟

102. 二叉树的层序遍历

public List<List<Integer>> levelOrder(TreeNode root) {    List<List<Integer>> res = new ArrayList<>();    if(root == null)return res;    Queue<TreeNode> queue = new LinkedList<>();    queue.offer(root);    while(!queue.isEmpty()){        List<Integer> list = new ArrayList<>();        //先把长度算好,因为queue长度一直在变        int len = queue.size();        for(int i=0;i<len;i++){            TreeNode temp = queue.poll();            list.add(temp.val);            if(temp.left !=null)queue.offer(temp.left);            if(temp.right !=null)queue.offer(temp.right);        }        res.add(list);    }    return res;}

429. N 叉树的层序遍历

queue的addAll()方法:加载此节点下的全部list
public List<List<Integer>> levelOrder(Node root) {    List<List<Integer>> res = new ArrayList<>();    if(root == null)return res;    Queue<Node> queue = new LinkedList<>();    queue.offer(root);    while(!queue.isEmpty()){        List<Integer> list = new ArrayList<>();        int size = queue.size();        for(int i=0;i<size;i++){            Node temp = queue.poll();            list.add(temp.val);            //加载此节点下的全部list            queue.addAll(temp.children);        }        res.add(list);    }    return res;}

107. 二叉树的层序遍历 II

LinkedList的addFirst()方法(前提: LinkedList

> res = new LinkedList<>();)

public List<List<Integer>> levelOrderBottom(TreeNode root) {    LinkedList<List<Integer>> res = new LinkedList<>();    if(root == null)return res;    Queue<TreeNode> queue = new LinkedList<>();    queue.offer(root);    while(!queue.isEmpty()){        List<Integer> list = new ArrayList<>(); ;        int len = queue.size();        for(int i=0;i<len;i++){            TreeNode temp = queue.poll();            list.add(temp.val);            if(temp.left !=null)queue.offer(temp.left);            if(temp.right !=null)queue.offer(temp.right);        }        //加到头部        res.addFirst(list);    }    return res;}

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

加上一个flag判断
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {    List<List<Integer>> res = new ArrayList<>();    if(root == null)return res;    Queue<TreeNode> queue = new LinkedList<>();    queue.offer(root);    //加上一个flag判断    boolean flag = true;    while(!queue.isEmpty()){        //此处用LinkedList        LinkedList<Integer> list = new LinkedList<>(); ;        int len = queue.size();        for(int i=0;i<len;i++){            TreeNode temp = queue.poll();            if(flag){                list.add(temp.val);            }else{                list.addFirst(temp.val);            }            if(temp.left !=null)queue.offer(temp.left);            if(temp.right !=null)queue.offer(temp.right);        }        //每遍历完一次换次值        flag =!flag;        res.add(list);    }    return res;}

958. 二叉树的完全性检验

public boolean isCompleteTree(TreeNode root) {    Queue<TreeNode> queue = new LinkedList<>();    queue.offer(root);    boolean flag = false;    while(!queue.isEmpty()){        TreeNode temp = queue.poll();        //如果queue不为空但弹出的值为空,说明左节点为空,不是完全二叉树        if(temp == null){            //只要为空改变符号            flag = true;            //跳过下面的操作            continue;        }        //不为空才能走到这一步        queue.offer(temp.left);        queue.offer(temp.right);    }    return true;}
错误实列(queue.offer放入null值也是值)
if(temp == null){    return false;}queue.offer(temp.left);queue.offer(temp.right);

199. 二叉树的右视图

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 len = queue.size();        for(int i=0;i<len;i++){            TreeNode temp = queue.poll();            if(temp.left !=null)queue.offer(temp.left);            if(temp.right !=null)queue.offer(temp.right);            //记录最后一个值加入res中            if(i==len-1)res.add(temp.val);        }    }    return res;}

116. 填充每个节点的下一个右侧节点指针

public Node connect(Node root) {    if(root == null)return root;    //先判断有无左节点    if(root.left != null){        root.left.next = root.right;        //再判断有无下一个节点        if(root.next != null){            root.right.next = root.next.left;        }    }    connect(root.left);    connect(root.right);    return root;}

117. 填充每个节点的下一个右侧节点指针 II

public Node connect(Node root) {    if(root == null)return root;    if(root.left != null && root.right != null){        root.left.next = root.right;    }    if(root.left != null && root.right == null){        //指向下一个节点        root.left.next = getNext(root.next);    }    if(root.right != null){        root.right.next = getNext(root.next);    }    // 先确保 root.right 下的节点的已完全连接,因 root.left 下的节点的连接    // 需要 root.left.next 下的节点的信息,若 root.right 下的节点未完全连    // 接(即先对 root.left 递归),则 root.left.next 下的信息链不完整,将    // 返回错误的信息。可能出现的错误情况如下图所示。此时,底层最左边节点将无    // 法获得正确的 next 信息:    //                  o root    //                 / \    //     root.left  o —— o  root.right    //               /    / \    //              o —— o   o    //             /        / \    //            o        o   o    connect(root.right);    connect(root.left);    return root;}public Node getNext(Node root){    if(root == null)return null;    if(root.left != null)return root.left;    if(root.right != null)return root.right;    if(root.next != null)return getNext(root.next);    return null;}

101. 对称二叉树

public boolean isSymmetric(TreeNode root) {    if(root==null)return true;    Queue<TreeNode> queue = new LinkedList();    queue.offer(root.left);    queue.offer(root.right);    while(!queue.isEmpty()){        //每次取出两个        TreeNode no1=queue.poll();        TreeNode no2=queue.poll();        //先判断        if(no1==null && no2==null)continue;        //注意是判断no1和no2的val        if(no1==null || no2==null || no1.val!=no2.val)return false;        //放入有顺序        queue.offer(no1.left);        queue.offer(no2.right);        queue.offer(no1.right);        queue.offer(no2.left);    }    return true;}

100. 相同的树

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

637. 二叉树的层平均值

public List<Double> averageOfLevels(TreeNode root) {        List<Double> res = new ArrayList<>();        if(root == null)return res;                Queue<TreeNode> queue = new LinkedList<>();        queue.offer(root);        while(!queue.isEmpty()){            Double d = 0.0;            int len = queue.size();            for(int i=0;i<len;i++){                TreeNode temp = queue.poll();                d += temp.val;                if(temp.left != null)queue.offer(temp.left);                if(temp.right != null)queue.offer(temp.right);            }            res.add(d/len);        }        return res;    }

------------------------------------

144. 二叉树的前序遍历

栈(非递归)
public List<Integer> preorderTraversal(TreeNode root) {    List<Integer> list = new ArrayList<>();    if(root == null)return list;    Stack<TreeNode> stack = new Stack<>();    stack.push(root);    while(!stack.isEmpty()){        TreeNode temp = stack.pop();        list.add(Integer.valueOf(temp.val));        if(temp.right!=null)stack.push(temp.right);//栈先进后出先放right        if(temp.left!=null)stack.push(temp.left);    }    return list;}

589. N叉树的前序遍历

非递归
public List<Integer> preorder(Node root) {    List<Integer> list = new ArrayList<>();    if(root == null)return list;    Stack<Node> stack = new Stack<>();    stack.push(root);    while(!stack.isEmpty()){        Node temp = stack.pop();        list.add(temp.val);        for(int i=temp.children.size()-1;i>=0;i--){            //最右边开始加            stack.push(temp.children.get(i));        }    }    return list;}

------------------------------------

94. 二叉树的中序遍历

public List<Integer> inorderTraversal(TreeNode root) {    List<Integer> list = new ArrayList<>();    Stack<TreeNode> stack = new Stack<>();    while(root != null || !stack.isEmpty()){        //一直往左        while(root != null){            stack.push(root);            root = root.left;        }        root = stack.pop();        list.add(root.val);        root = root.right;    }    return list;}

98. 验证二叉搜索树

class Solution {   public boolean isValidBST(TreeNode root) {        return validate(root, Long.MIN_VALUE, Long.MAX_VALUE);//放入root节点,最大值最小值不能为Integer,例:等于[2147483647]时为false则不对    }​   public boolean validate(TreeNode node,long min,long max){       if(node==null)return true;       if(node.val<=min || node.val>=max)return false;//如果此节点的值小于等于最小值或大于等于最大值       return validate(node.left,min,node.val) && validate(node.right,node.val,max);       //向左将max换为node.val,看是否左边的值都小于上一个节点的值       //向右将min换为node.val,看是否右边的值都大于于上一个节点的值   }}

783. 二叉搜索树节点最小距离

TreeNode pre = null;//记录前一个节点int res = Integer.MAX_VALUE;public int minDiffInBST(TreeNode root) {    dfs(root);    return res;}public void dfs(TreeNode root){    if(root == null)return;    //一直往左,直到为null,记录每一个数和上一个数pre的比较    dfs(root.left);    if(pre != null){        res = Math.min(res,root.val-pre.val);//记录最小    }    pre = root;    dfs(root.right);}

230. 二叉搜索树中第K小的元素

class Solution {    int count = 0;    int res;    public int kthSmallest(TreeNode root, int k) {        dfs(root,k);        return res;    }    public void dfs(TreeNode root,int k){        if(root == null)return;        dfs(root.left,k);        count++;        //找到了记录一下res值即可        if(count == k)res = root.val;        dfs(root.right,k);    }}

671. 二叉树中第二小的节点

问题可以转化为求左右子树的最小值,如果左右子树最小值都大于根节点的值取较小的值。其他情况取左右子树较大的值。
public int findSecondMinimumValue(TreeNode root) {    return helper(root,root.val);}​public int helper(TreeNode root,int minVal){    //叶子端点    if(root==null){        return -1;    }    //如果当前结点值>根节点,那么不用再遍历它的子节点,直接返回该值    if(root.val>minVal){        return root.val;    }​    //否则,即当前结点值==根节点,则需要在两棵子树找目标值结点    int l=helper(root.left,minVal);    int r=helper(root.right,minVal);    //如果两棵子树均存在大于最小值的节点,那么返回较小的那一个    if(l!=-1&&r!=-1){        return Math.min(l,r);    }else{//否则,其余情况均返回较大的那一个        return Math.max(l,r);    }}

226. 翻转二叉树

//利用中序遍历class Solution {    public TreeNode invertTree(TreeNode root) {        if (root == null) return null;        invertTree(root.left); // 递归找到左节点        TreeNode temp= root.right; // 保存右节点        root.right = root.left;        root.left = temp;        // 递归找到右节点 继续交换 : 因为此时左右节点已经交换了,所以此时的右节点为root.left        invertTree(root.left);         return root;    }}

------------------------------------

145. 二叉树的后序遍历

递归
class Solution {    public List<Integer> postorderTraversal(TreeNode root) {        List<Integer> res = new ArrayList<>();        last(root,res);        return res;    }    public void last(TreeNode root,List<Integer> res){        if(root==null)return;        last(root.left,res);        last(root.right,res);        res.add(root.val);    }}
迭代
class Solution {    public List<Integer> postorderTraversal(TreeNode root) {        List<Integer> res = new ArrayList<>();        Stack<TreeNode> stack = new Stack<>();        //记录前一个节点        TreeNode cur=null;        while(root!=null || !stack.isEmpty()){            while(root!=null){                stack.push(root);                root=root.left;            }            root = stack.peek();            //防止右边被遍历完之后还接着遍历,找个节点记录已完成的右节点,如果右节点不为空且已被记录那直接弹出当前节点            if(root.right==null || root.right==cur){                res.add(root.val);                //弹出的节点被记录                cur=stack.pop();                root=null;            }else{                root=root.right;            }        }        return res;    }}

590. N叉树的后序遍历

递归
class Solution {
    List<Integer> res = new ArrayList<>();
    public List<Integer> postorder(Node root) {
        last(root);
        return res;
    }
    public void last(Node root){
        if(root == null)return;
        for(int i=0;i<root.children.size();i++){
            last(root.children.get(i));
        }
        res.add(root.val);
    }
}

------------------------------------

112. 路径总和

递归
class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        //节点为空时直接返回false
       if(root==null)return false;
        //为节点时判断节点值是否等于当前剩余值
        if(root.left==null && root.right==null){
            return sum==root.val;
        }
        //一真则真true
        return hasPathSum(root.left,sum-root.val) || hasPathSum(root.right,sum-root.val);
    }
}

113. 路径总和 II

public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> list = new ArrayList<>();
    dfs(root,targetSum,res,list);
    return res;
}
public static void dfs(TreeNode root, int targetSum, List<List<Integer>> res,List<Integer> list){
    if(root == null)return;
    list.add(root.val);
    if(targetSum == root.val && root.left == null && root.right == null){
        //注意:把list放进new ArrayList<>()里
        res.add(new ArrayList<>(list));
        list.remove(list.size()-1);
        return;
    }
    //每次把总值-root.val
    dfs(root.left,targetSum-root.val,res,list);
    dfs(root.right,targetSum-root.val,res,list);
    //回溯
    list.remove(list.size()-1);
}

------------------------------------

剑指 Offer 07. 重建二叉树

image.png

//利用原理,先序遍历的第一个节点就是根。在中序遍历中通过根 区分哪些是左子树的,哪些是右子树的
//左右子树,递归
HashMap<Integer, Integer> map = new HashMap<>();//标记中序遍历
int[] preorder;//保留的先序遍历

public TreeNode buildTree(int[] preorder, int[] inorder) {
    this.preorder = preorder;
    for(int i=0;i<inorder.length;i++){
        map.put(inorder[i],i);
    }
    return buildTree(0,preorder.length-1,0,inorder.length-1);
}
public TreeNode buildTree(int preL,int preR,int inL,int inR){
    if(preL>preR || inL>inR){//左大于右就退出
        return null;
    }
    int pivot = map.get(preorder[preL]);//从先序的头找出中序的pivot节点
    TreeNode root = new TreeNode(preorder[preL]);//把头节点拿出来
    root.left = buildTree(preL+1,pivot-inL+preL,inL,pivot-1);//递归先序的左边和中序的左边
    root.right = buildTree(pivot-inL+preL+1,preR,pivot+1,inR);//递归先序的右边和中序的右边
    return root;
}

110. 平衡二叉树

从下往上遍历
class Solution {
    boolean res=true;//做一个标记
    public boolean isBalanced(TreeNode root) {
        recur(root);
        return res;
    }
    private int recur(TreeNode root) {
        if(root==null)return 0;
        int left=recur(root.left)+1;//直接先把节点往左遍历到最底端
        int right=recur(root.right)+1;
        if(Math.abs(left-right)>1)res=false;//一旦有一个节点相差长度大于1了,把标记改为false
        return Math.max(left,right);//返回较长的那一边
    }
}

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

TreeNode res;
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    lca(root,p,q);
    return res;
}
public void lca(TreeNode root, TreeNode p, TreeNode q){
    //乘值小于等于0时,说明找到了
    if((root.val-p.val)*(root.val-q.val) <= 0){//此节点以下的节点,公共祖先就是此节点(所以有等于0)
        res = root;
    }else if(root.val-p.val < 0 && root.val-q.val < 0){//都小于0则在右边
        lowestCommonAncestor(root.right,p,q);
    }else{
        lowestCommonAncestor(root.left,p,q);
    }
}

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

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    if(root == null || root == p || root == q) return root;
    TreeNode left = lowestCommonAncestor(root.left, p, q);
    TreeNode right = lowestCommonAncestor(root.right, p, q);
    //左等于空返回右,右等于空返回左,都等于空随便返回一个(这里返回了左)
    if(left == null) return right;
    if(right == null) return left;
    //左右都不为空说明找到了返回root
    return root;
}

104. 二叉树的最大深度

dfs深度优先
class Solution {
    public int maxDepth(TreeNode root) {
        if(root==null){
            return 0;
        }else{
            int left=maxDepth(root.left);
            int right=maxDepth(root.right);
            return Math.max(left,right)+1;
        } 
    }
}

111. 二叉树的最小深度

class Solution {
    public int minDepth(TreeNode root) {
        if(root==null){
            return 0;
        }else{
            int left=minDepth(root.left);
            int right=minDepth(root.right);
            //1.如果左孩子和右孩子有为空的情况,直接返回m1+m2+1
            //2.如果都不为空,返回较小深度+1
            return root.left == null || root.right == null ? left + right + 1 : Math.min(left,right) + 1;
        } 
    }
}

687. 最长同值路径