牛客top100 -自刷打卡day2+3 - 二叉树


二叉树

BM23二叉树的前序遍历

二叉树的前序遍历_牛客题霸_牛客网 (nowcoder.com)

  • 递归, 秒
import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @return int整型一维数组
     */
    List<Integer> list = new ArrayList<>();
    
    public void preorder(TreeNode root){
        if(root == null) {
            return ;
        }
        list.add(root.val);
        preorder(root.left);
        preorder(root.right);
        
    }
    public int[] preorderTraversal (TreeNode root) {
        // write code here
        if(root == null) return new int[0];
        preorder(root);
        int[] res = new int[list.size()];
        
        for(int i = 0; i < list.size(); i++) {
            res[i] = list.get(i);
        }
        return res;
    }
}
  • 非递归

BM24二叉树的中序遍历

二叉树的中序遍历_牛客题霸_牛客网 (nowcoder.com)

  • 递归
import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @return int整型一维数组
     */
    ArrayList<Integer> list = new ArrayList<>();
    
    public void inorderHelp(TreeNode root){
        if(root == null) return ;
        inorderHelp(root.left);
        list.add(root.val);
        inorderHelp(root.right);
    }
    public int[] inorderTraversal (TreeNode root) {
        // write code here
        if(root == null) return new int[0];
        inorderHelp(root);
        int[] res = new int[list.size()];
        for(int i = 0; i < res.length; i++) {
            res[i] = list.get(i);
        }
        return res;
    }
}
  • 非递归
import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @return int整型一维数组
     */
    public int[] inorderTraversal (TreeNode root) {
        // write code here
        if(root == null) return new int[0];
        List<Integer> list = new ArrayList<>();
        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();
            list.add(top.val);
            cur = top.right;
        }
        int []res = new int[list.size()];
        for(int i = 0; i < res.length; i++) {
            res[i] = list.get(i);
        }
        return res
;
    }
}

BM25二叉树的后序遍历

二叉树的后序遍历_牛客题霸_牛客网 (nowcoder.com)

  • 非递归
import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @return int整型一维数组
     */
    public int[] postorderTraversal (TreeNode root) {
        // write code here
        if(root == null) return new int[0];
        Stack<TreeNode> stack = new Stack<>();
        List<Integer> list = new ArrayList<>();
        TreeNode cur = root;
        TreeNode pre = 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 == pre){
                stack.pop();
                list.add(top.val);
                pre = top;
            }else{
                cur = top.right;
            }
        }
        int []res = new int[list.size()];
        for(int i = 0; i < res.length; i++) {
            res[i] = list.get(i);
        }
        return res;
    }
}

BM26求二叉树的层序遍历

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     *
     * @param root TreeNode类
     * @return int整型ArrayList<ArrayList<>>
     */
    public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();

        if(root == null) return res;
        // write code here
        Queue<TreeNode> q = new LinkedList<>();
        TreeNode cur = root;
        q.offer(cur);
        while (!q.isEmpty()) {
            ArrayList<Integer> list = new ArrayList<>();
            int size = q.size();
            for(int i = 0; i < size; i++){
                TreeNode top = q.poll();
                list.add(top.val);
                if(top.left != null) q.offer(top.left);
                if(top.right != null) q.offer(top.right);
            }
            res.add(list);
        }
        return res;


    }
}

BM27按之字形顺序打印二叉树

按之字形顺序打印二叉树_牛客题霸_牛客网 (nowcoder.com)

  • Collections.reverse, 逆序输出
import java.util.ArrayList;
import java.util.*;
/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        if (pRoot == null) return res;
        Queue<TreeNode> queue = new LinkedList<>();
        TreeNode cur = pRoot;
        queue.offer(cur);
        boolean iflag = true;
        while (!queue.isEmpty()) {
            ArrayList<Integer> list = new ArrayList<>();
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode top = queue.poll();
                list.add(top.val);
                if (top.left != null) queue.offer(top.left);
                if (top.right != null) queue.offer(top.right);
            }
            if (iflag) res.add(list);
            else {
                Collections.reverse(list);
                res.add(list);

            }
            iflag = !iflag;
        }
        return res;
    }

}

BM28二叉树的最大深度

二叉树的最大深度

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    public int maxDepth (TreeNode root) {
        // write code here
        if(root == null) return 0;
        if(root.left == null && root.right == null) {
            return 1;
        }
        int left = maxDepth(root.left);
        int right = maxDepth(root.right);
        return left > right ? left + 1 : right + 1;
    }
}

BM29二叉树中和为某一值的路径(一)

二叉树中和为某一值的路径(一)

  • 注意要结束条件, 当节点的左节点和右节点都为空且此时的sum为0的时候, 这时候就表明找到了
import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @param sum int整型 
     * @return bool布尔型
     */
    public boolean hasPathSum (TreeNode root, int sum) {
        // write code here
        if(root == null) return false;
        return dfs(root, sum);
    }
    public boolean dfs(TreeNode root, int sum) {
        if(root == null) {
            return false;
        }
        if(root.left == null && root.right == null && sum - root.val == 0) return true;
        return dfs(root.left, sum - root.val) || dfs(root.right, sum - root.val);


    }
}

BM30二叉搜索树与双向链表

二叉搜索树与双向链表

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public TreeNode head = null;
    public TreeNode pre = null;
    public TreeNode Convert(TreeNode pRootOfTree) {
        if(pRootOfTree == null) {
            return null;
        }
        Convert(pRootOfTree.left);
        if(pre == null){
            head = pRootOfTree;
            pre = pRootOfTree;
        }else{
            pre.right = pRootOfTree;
            pRootOfTree.left = pre;
            pre = pRootOfTree;
        }
        Convert(pRootOfTree.right);
        return head;
    }
}

BM31对称的二叉树

对称的二叉树

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    boolean isSame(TreeNode root1, TreeNode root2) {
        if(root1 == null && root2 == null) return true;
        if(root1 == null || root2 == null) return false;
        if (root1.val != root2.val) {
            return false;
        }
        return isSame(root1.left, root2.right) && isSame(root1.right, root2.left);
    }
    boolean isSymmetrical(TreeNode pRoot) {
        if (pRoot == null) return true;
        return isSame(pRoot, pRoot);
    }
}

思路简单33.53%

视频题解

BM32合并二叉树

合并二叉树

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param t1 TreeNode类 
     * @param t2 TreeNode类 
     * @return TreeNode类
     */
    public TreeNode mergeTrees (TreeNode t1, TreeNode t2) {
        // write code here
        if(t1 == null) return t2;
        if(t2 == null) return t1;
        TreeNode head = new TreeNode(-1);
        if(t1 != null && t2 != null) {
            head.val = t1.val + t2.val;
        }
        
        head.left = mergeTrees(t1.left, t2.left);
        head.right = mergeTrees(t1.right, t2.right);
        return head;
    }
}

思路简单72.89%

视频题解

BM33二叉树的镜像

二叉树的镜像

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param pRoot TreeNode类
     * @return TreeNode类
     */
    public TreeNode Mirror (TreeNode pRoot) {
        // write code here
        if (pRoot == null) return null;
        TreeNode left = Mirror(pRoot.left);
        TreeNode right = Mirror(pRoot.right);
        //交换
        pRoot.left = right;
        pRoot.right = left;
        return pRoot;
    }
}

思路简单67.58%

BM34判断是不是二叉搜索树

判断是不是二叉搜索树

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @return bool布尔型
     */
    private boolean BST(TreeNode root, int left, int right){
        if(root == null) return true;
        // write code here
        if(root.val<=left||root.val>=right){
            return false;
        }
        return BST(root.left, left, root.val) && BST(root.right, root.val, right);
        
    }
    public boolean isValidBST (TreeNode root) {
        return BST(root, Integer.MIN_VALUE,  Integer.MAX_VALUE);
    }
}

思路中等33.42%

BM35判断是不是完全二叉树

判断是不是完全二叉树

思路中等39.10%

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param root TreeNode类
     * @return bool布尔型
     */
    public boolean isCompleteTree (TreeNode root) {
        // write code here
        if (root == null) return false;
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        while (!q.isEmpty()) {
            TreeNode c = q.poll();
            if (c != null) {
                q.offer(c.left);
                q.offer(c.right);
            } else {
                break;
            }
        }
        //遍历第二次
        while (!q.isEmpty()) {
            TreeNode node = q.peek();
            if (node == null) {
                q.poll();
            } else {
                return false;
            }
        }
        return true;
    }
}

BM36判断是不是平衡二叉树

判断是不是平衡二叉树

public class Solution {
    public int depth(TreeNode root){
        if(root == null) {
            return 0;
        }
        int lh = depth(root.left) + 1;
        int rh = depth(root.right) + 1;
        return lh > rh ? lh : rh;
    }
    public boolean IsBalanced_SolutionHelp(TreeNode root){
        int left = depth(root.left);
        int right = depth(root.right);
        if(Math.abs(left - right) <= 1){
            return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
        }
        return false;

    }
    public boolean IsBalanced_Solution(TreeNode root) {
        if(root == null) {
            return true;
        }
        return IsBalanced_SolutionHelp(root);
    }
}

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

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

思路简单49.56%

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @param p int整型 
     * @param q int整型 
     * @return int整型
     */
    public int lowestCommonAncestor (TreeNode root, int p, int q) {
        // write code here
        if(root == null) return -1;
        if((p >= root.val && q <= root.val) || (p <= root.val && q >= root.val)){
            return root.val;
        }else if(p <= root.val && q <= root.val){
            return lowestCommonAncestor(root.left, p, q);
        }else{
            return lowestCommonAncestor(root.right, p, q);
        }
    }
}
import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @param p int整型 
     * @param q int整型 
     * @return int整型
     */
    public int lowestCommonAncestor (TreeNode root, int p, int q) {
        // write code here
        if(root == null) return -1;
        if(root.val == p){
            return p;
        }
        if(root.val == q){
            return q;
        }
        int left = lowestCommonAncestor(root.left, p, q);
        int right = lowestCommonAncestor(root.right, p, q);
        if(left != -1 && right != -1){
            return root.val;
        }else if (left != -1){
            return left;
        }else if(right != -1){
            return right;
        }

        return -1;
    }
}

BM38在二叉树中找到两个节点的最近公共祖先

在二叉树中找到两个节点的最近公共祖先

思路中等45.26%

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @param o1 int整型 
     * @param o2 int整型 
     * @return int整型
     */
    public int lowestCommonAncestor (TreeNode root, int o1, int o2) {
        // write code here
        if(root == null) return -1;
        if(root.val == o1){
            return o1;
        }
        if(root.val == o2){
            return o2;
        }
        int left = lowestCommonAncestor(root.left, o1, o2);
        int right = lowestCommonAncestor(root.right, o1, o2);
        if(left != -1 && right != -1){
            return root.val;
        }else if (left != -1){
            return left;
        }else if(right != -1){
            return right;
        }
 
        return -1;
    }
   
}                                                                                         

BM39序列化二叉树

序列化二叉树

思路较难25.04%

  • …过了

BM40重建二叉树

重建二叉树

思路中等27.70%

import java.util.*;
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int preIndex = 0;
    public TreeNode reConstructBinaryTree(int [] pre,int [] vin) {
        return buildTreeChild(pre, vin, 0, vin.length - 1); 
    }
    public TreeNode buildTreeChild(int[] pre, int[] vin, int begin, int end){
        if(begin > end) return null;
        TreeNode root = new TreeNode(pre[preIndex]);
        //找到中序遍历中节点位置
        int rootIndex = findInoederIndex(vin, begin, end, root.val);
        preIndex++;
        root.left = buildTreeChild(pre, vin, begin, rootIndex - 1);
        root.right = buildTreeChild(pre, vin, rootIndex + 1, end);
        return root;
    }
    public int findInoederIndex(int[] inorder, int begin, int end, int val){
        for(int i = begin; i <= end; i++) {
            if(inorder[i] == val){
                return i;
            }
        }
        return -1;
    }
}

BM41输出二叉树的右视图

输出二叉树的右视图

思路中等56.99%

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 求二叉树的右视图
     * @param xianxu int整型一维数组 先序遍历
     * @param zhongxu int整型一维数组 中序遍历
     * @return int整型一维数组
     */
    private HashMap<Integer, Integer> ans = new HashMap<>();
    private HashMap<Integer, Integer> map = new HashMap<>();
    public int[] solve (int[] xianxu, int[] zhongxu) {
        // write code here
        for (int i = 0; i < zhongxu.length; i++) {
            map.put(zhongxu[i], i);
        }
        build(xianxu, zhongxu, 0, xianxu.length - 1, 0);
        int[] tmp = new int[ans.size()];
        for (int i = 0; i < ans.size(); i++) {
            tmp[i] = ans.get(i);
        }
        return tmp;
    }
    //pIndex表示先序遍历的顺序i
    public int pIndex = 0;
    //index表示层级
    public void build(int[] xianxu, int[] zhongxu, int left, int right, int index) {
        if (left > right) {
            return ;
        }
        //找到在中序遍历中pIndex对应的值的下标
        int pindex = map.get(xianxu[pIndex++]);
        //左子树
        build(xianxu, zhongxu, left, pindex - 1, index + 1);
        //右子树
        build(xianxu, zhongxu, pindex + 1, right, index + 1);
        ans.put(index, zhongxu[pindex]);
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
题目要求:给定一个二叉树和一个整数target,找出所有从根节点到叶子节点路径之和等于target的路径。 解题思路:可以使用深度优先搜索(DFS)的方法来解决该问题。首先定义一个辅助函数来进行递归搜索,该辅助函数的参数包括当前节点、当前路径、当前路径的和以及目标和。在搜索过程中,需要维护一个数组来保存当前节点到根节点的路径。搜索过程如下: 1. 如果当前节点为空,则返回。 2. 将当前节点的值添加到当前路径中。 3. 将当前节点的值累加到当前路径的和中。 4. 如果当前节点是叶子节点,且当前路径的和等于目标和,则将当前路径添加到结果中。 5. 递归地搜索当前节点的左子树和右子树,并传递更新后的当前路径和当前路径的和。 最后,在主函数中调用辅助函数,并返回结果即可。 以下是题目的完整代码实现: ```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def pathSum(root, target): def dfs(node, path, path_sum, target, res): if not node: return path.append(node.val) path_sum += node.val if not node.left and not node.right: # 当前节点是叶子节点 if path_sum == target: res.append(path[:]) # 注意需要复制一份path,否则会出现问题 dfs(node.left, path, path_sum, target, res) dfs(node.right, path, path_sum, target, res) path.pop() # 回溯到父节点,去掉当前节点 path_sum -= node.val res = [] dfs(root, [], 0, target, res) return res ``` 这样就能找出所有满足路径和等于目标和的路径了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值