一篇文章搞定面试中的二叉树

转载自  IOExceptioner  算法与数据结构

在上一篇介绍二叉树( Android面试题算法之二叉树 、红黑树详细分析,看了都说好),没看的读者建议先去了解了解,接下来再给大家带来一篇关于二叉树的文章。

最近总结了一些数据结构和算法相关的题目,这是第一篇文章,关于二叉树的。
先上二叉树的数据结构:

class TreeNode{
   int val;
   //左孩子
   TreeNode left;
   //右孩子
   TreeNode right;
}

二叉树的题目普遍可以用递归和迭代的方式来解

1. 求二叉树的最大深度

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

2. 求二叉树的最小深度

    int getMinDepth(TreeNode root){
       if(root == null){
           return 0;
       }
       return getMin(root);
   }
   int getMin(TreeNode root){
       if(root == null){
           return Integer.MAX_VALUE;
       }
       if(root.left == null&&root.right == null){
           return 1;
       }
       return Math.min(getMin(root.left),getMin(root.right)) + 1;
   }

3. 求二叉树中节点的个数

    int numOfTreeNode(TreeNode root){
       if(root == null){
           return 0;
       }
       int left = numOfTreeNode(root.left);
       int right = numOfTreeNode(root.right);
       return left + right + 1;
   }

4. 求二叉树中叶子节点的个数

    int numsOfNoChildNode(TreeNode root){
       if(root == null){
           return 0;
       }
       if(root.left==null&&root.right==null){
           return 1;
       }
       return numsOfNodeTreeNode(root.left)+numsOfNodeTreeNode(root.right);
   }

5. 求二叉树中第k层节点的个数

        int numsOfkLevelTreeNode(TreeNode root,int k){
           if(root == null||k<1){
               return 0;
           }
           if(k==1){
               return 1;
           }
           int numsLeft = numsOfkLevelTreeNode(root.left,k-1);
           int numsRight = numsOfkLevelTreeNode(root.right,k-1);
           return numsLeft + numsRight;
       }

6. 判断二叉树是否是平衡二叉树

    boolean isBalanced(TreeNode node){
       return maxDeath2(node)!=-1;
   }
   int maxDeath2(TreeNode node){
       if(node == null){
           return 0;
       }
       int left = maxDeath2(node.left);
       int right = maxDeath2(node.right);
       if(left==-1||right==-1||Math.abs(left-right)>1){
           return -1;
       }
       return Math.max(left, right) + 1;
   }

7.判断二叉树是否是完全二叉树

什么是完全二叉树呢?参见

    boolean isCompleteTreeNode(TreeNode root){
       if(root == null){
           return false;
       }
       Queue<TreeNode> queue = new LinkedList<TreeNode>();
       queue.add(root);
       boolean result = true;
       boolean hasNoChild = false;
       while(!queue.isEmpty()){
           TreeNode current = queue.remove();
           if(hasNoChild){
               if(current.left!=null||current.right!=null){
                   result = false;
                   break;
               }
           }else{
               if(current.left!=null&&current.right!=null){
                   queue.add(current.left);
                   queue.add(current.right);
               }else if(current.left!=null&&current.right==null){
                   queue.add(current.left);
                   hasNoChild = true;
               }else if(current.left==null&&current.right!=null){
                   result = false;
                   break;
               }else{
                   hasNoChild = true;
               }
           }
       }
       return result;
   }

8. 两个二叉树是否完全相同

    boolean isSameTreeNode(TreeNode t1,TreeNode t2){
       if(t1==null&&t2==null){
           return true;
       }
       else if(t1==null||t2==null){
           return false;
       }
       if(t1.val != t2.val){
           return false;
       }
       boolean left = isSameTreeNode(t1.left,t2.left);
       boolean right = isSameTreeNode(t1.right,t2.right);
       return left&&right;
   }

9. 两个二叉树是否互为镜像

    boolean isMirror(TreeNode t1,TreeNode t2){
       if(t1==null&&t2==null){
           return true;
       }
       if(t1==null||t2==null){
           return false;
       }
       if(t1.val != t2.val){
           return false;
       }
       return isMirror(t1.left,t2.right)&&isMirror(t1.right,t2.left);
   }

10. 翻转二叉树or镜像二叉树

    TreeNode mirrorTreeNode(TreeNode root){
       if(root == null){
           return null;
       }
       TreeNode left = mirrorTreeNode(root.left);
       TreeNode right = mirrorTreeNode(root.right);
       root.left = right;
       root.right = left;
       return root;
   }

11. 求两个二叉树的最低公共祖先节点

    TreeNode getLastCommonParent(TreeNode root,TreeNode t1,TreeNode t2){
       if(findNode(root.left,t1)){
           if(findNode(root.right,t2)){
               return root;
           }else{
               return getLastCommonParent(root.left,t1,t2);
           }
       }else{
           if(findNode(root.left,t2)){
               return root;
           }else{
               return getLastCommonParent(root.right,t1,t2)
           }
       }
   }
   // 查找节点node是否在当前 二叉树中
   boolean findNode(TreeNode root,TreeNode node){
       if(root == null || node == null){
           return false;
       }
       if(root == node){
           return true;
       }
       boolean found = findNode(root.left,node);
       if(!found){
           found = findNode(root.right,node);
       }
       return found;
   }

12. 二叉树的前序遍历

迭代解法

    ArrayList<Integer> preOrder(TreeNode root){
       Stack<TreeNode> stack = new Stack<TreeNode>();
       ArrayList<Integer> list = new ArrayList<Integer>();
       if(root == null){
           return list;
       }
       stack.push(root);
       while(!stack.empty()){
           TreeNode node = stack.pop();
           list.add(node.val);
           if(node.right!=null){
               stack.push(node.right);
           }
           if(node.left != null){
               stack.push(node.left);
           }
       }
       return list;
   }

递归解法

    ArrayList<Integer> preOrderReverse(TreeNode root){
       ArrayList<Integer> result = new ArrayList<Integer>();
       preOrder2(root,result);
       return result;
   }
   void preOrder2(TreeNode root,ArrayList<Integer> result){
       if(root == null){
           return;
       }
       result.add(root.val);
       preOrder2(root.left,result);
       preOrder2(root.right,result);
   }

13. 二叉树的中序遍历

    ArrayList<Integer> inOrder(TreeNode root){
       ArrayList<Integer> list = new ArrayList<<Integer>();
       Stack<TreeNode> stack = new Stack<TreeNode>();
       TreeNode current = root;
       while(current != null|| !stack.empty()){
           while(current != null){
               stack.add(current);
               current = current.left;
           }
           current = stack.peek();
           stack.pop();
           list.add(current.val);
           current = current.right;
       }
       return list;
   }

14.二叉树的后序遍历

    ArrayList<Integer> postOrder(TreeNode root){
       ArrayList<Integer> list = new ArrayList<Integer>();
       if(root == null){
           return list;
       }
       list.addAll(postOrder(root.left));
       list.addAll(postOrder(root.right));
       list.add(root.val);
       return list;
   }

15.前序遍历和后序遍历构造二叉树

    TreeNode buildTreeNode(int[] preorder,int[] inorder){
       if(preorder.length!=inorder.length){
           return null;
       }
       return myBuildTree(inorder,0,inorder.length-1,preorder,0,preorder.length-1);
   }
   TreeNode myBuildTree(int[] inorder,int instart,int inend,int[] preorder,int prestart,int preend){
       if(instart>inend){
           return null;
       }
       TreeNode root = new TreeNode(preorder[prestart]);
       int position = findPosition(inorder,instart,inend,preorder[start]);
       root.left = myBuildTree(inorder,instart,position-1,preorder,prestart+1,prestart+position-instart);
       root.right = myBuildTree(inorder,position+1,inend,preorder,position-inend+preend+1,preend);
       return root;
   }
   int findPosition(int[] arr,int start,int end,int key){
       int i;
       for(i = start;i<=end;i++){
           if(arr[i] == key){
               return i;
           }
       }
       return -1;
   }

16.在二叉树中插入节点

    TreeNode insertNode(TreeNode root,TreeNode node){
       if(root == node){
           return node;
       }
       TreeNode tmp = new TreeNode();
       tmp = root;
       TreeNode last = null;
       while(tmp!=null){
           last = tmp;
           if(tmp.val>node.val){
               tmp = tmp.left;
           }else{
               tmp = tmp.right;
           }
       }
       if(last!=null){
           if(last.val>node.val){
               last.left = node;
           }else{
               last.right = node;
           }
       }
       return root;
   }

17.输入一个二叉树和一个整数,打印出二叉树中节点值的和等于输入整数所有的路径

    void findPath(TreeNode r,int i){
       if(root == null){
           return;
       }
       Stack<Integer> stack = new Stack<Integer>();
       int currentSum = 0;
       findPath(r, i, stack, currentSum);
   }
   void findPath(TreeNode r,int i,Stack<Integer> stack,int currentSum){
       currentSum+=r.val;
       stack.push(r.val);
       if(r.left==null&&r.right==null){
           if(currentSum==i){
               for(int path:stack){
                   System.out.println(path);
               }
           }
       }
       if(r.left!=null){
           findPath(r.left, i, stack, currentSum);
       }
       if(r.right!=null){
           findPath(r.right, i, stack, currentSum);
       }
       stack.pop();
   }

18.二叉树的搜索区间

给定两个值 k1 和 k2(k1 < k2)和一个二叉查找树的根节点。找到树中所有值在 k1 到 k2 范围内的节点。即打印所有x (k1 <= x <= k2) 其中 x 是二叉查找树的中的节点值。返回所有升序的节点值。

    ArrayList<Integer> result;
   ArrayList<Integer> searchRange(TreeNode root,int k1,int k2){
       result = new ArrayList<Integer>();
       searchHelper(root,k1,k2);
       return result;
   }
   void searchHelper(TreeNode root,int k1,int k2){
       if(root == null){
           return;
       }
       if(root.val>k1){
           searchHelper(root.left,k1,k2);
       }
       if(root.val>=k1&&root.val<=k2){
           result.add(root.val);
       }
       if(root.val<k2){
           searchHelper(root.right,k1,k2);
       }
   }

19.二叉树的层次遍历

    ArrayList<ArrayList<Integer>> levelOrder(TreeNode root){
       ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
       if(root == null){
           return result;
       }
       Queue<TreeNode> queue = new LinkedList<TreeNode>();
       queue.offer(root);
       while(!queue.isEmpty()){
           int size = queue.size();
           ArrayList<<Integer> level = new ArrayList<Integer>():
           for(int i = 0;i < size ;i++){
               TreeNode node = queue.poll();
               level.add(node.val);
               if(node.left != null){
                   queue.offer(node.left);
               }
               if(node.right != null){
                   queue.offer(node.right);
               }
           }
           result.add(Level);
       }
       return result;
   }

20.二叉树内两个节点的最长距离

二叉树中两个节点的最长距离可能有三种情况:
1.左子树的最大深度+右子树的最大深度为二叉树的最长距离
2.左子树中的最长距离即为二叉树的最长距离
3.右子树种的最长距离即为二叉树的最长距离
因此,递归求解即可

private static class Result{  
   int maxDistance;  
   int maxDepth;  
   public Result() {  
   }  
   public Result(int maxDistance, int maxDepth) {  
       this.maxDistance = maxDistance;  
       this.maxDepth = maxDepth;  
   }  
}  
   int getMaxDistance(TreeNode root){
     return getMaxDistanceResult(root).maxDistance;
   }
   Result getMaxDistanceResult(TreeNode root){
       if(root == null){
           Result empty = new Result(0,-1);
           return empty;
       }
       Result lmd = getMaxDistanceResult(root.left);
       Result rmd = getMaxDistanceResult(root.right);
       Result result = new Result();
       result.maxDepth = Math.max(lmd.maxDepth,rmd.maxDepth) + 1;
       result.maxDistance = Math.max(lmd.maxDepth + rmd.maxDepth,Math.max(lmd.maxDistance,rmd.maxDistance));
       return result;
   }

21.不同的二叉树

给出 n,问由 1…n 为节点组成的不同的二叉查找树有多少种?

    int numTrees(int n ){
       int[] counts = new int[n+2];
       counts[0] = 1;
       counts[1] = 1;
       for(int i = 2;i<=n;i++){
           for(int j = 0;j<i;j++){
               counts[i] += counts[j] * counts[i-j-1];
           }
       }
       return counts[n];
   }

22.判断二叉树是否是合法的二叉查找树(BST)

一棵BST定义为:
节点的左子树中的值要严格小于该节点的值。
节点的右子树中的值要严格大于该节点的值。
左右子树也必须是二叉查找树。
一个节点的树也是二叉查找树。

    public int lastVal = Integer.MAX_VALUE;
   public boolean firstNode = true;
   public boolean isValidBST(TreeNode root) {
       // write your code here
       if(root==null){
           return true;
       }
       if(!isValidBST(root.left)){
           return false;
       }
       if(!firstNode&&lastVal >= root.val){
           return false;
       }
       firstNode = false;
       lastVal = root.val;
       if (!isValidBST(root.right)) {
           return false;
       }
       return true;
   }

深刻的理解这些题的解法思路,在面试中的二叉树题目就应该没有什么问题


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/331303.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

清洁代码_清洁单元测试

清洁代码编写使用JUnit和某些模拟库的“单元测试”测试很容易。 即使测试甚至不是单元测试并提供可疑的价值&#xff0c;它们也可能产生使某些涉众满意的代码覆盖范围。 编写单元测试&#xff08;在理论上是单元测试&#xff0c;但是比基础代码更复杂&#xff09;因此也很容易编…

jvm(6)-Class字节码文件结构总结

【0】README 0.1&#xff09;本文总结于 Clas字节码文件&#xff0c;旨在理清 Class字节码文件的大体结构&#xff1b; 【1】干货开始 对上图的分析&#xff08;Analysis&#xff09;&#xff1a;A1&#xff09;offset0 A1.1&#xff09;头四个字节为CAFEBABE&#xff1a;表示…

Android面试题算法之二叉树

转载自 qing的世界 程序员小乐文章目录 前言二叉树的递归&#xff08;深度优先&#xff09;处理二叉树的层序处理(广度优先)总结“一、前言今年可谓是跌宕起伏的一年&#xff0c;幸好结局还算是圆满。开年的时候由于和公司CTO有过节&#xff0c;被"打入冷宫"&#…

java 读取 文本块_Java文本块

java 读取 文本块文本块是JDK增强建议&#xff08; JEP 355 &#xff09;&#xff0c;可以在JDK 13和14中用作预览语言功能。它计划在JDK 15中成为永久性功能。文本块是跨越多行并且不需要的String文字。对于大多数转义序列。 动机 在标准Java字符串中嵌入XML&#xff0c;JSON…

代理模式之虚拟代理(仅了解)

【0】README0.1&#xff09;本文全文转自 “head first 设计模式”&#xff0c;旨在了解 虚拟代理动态代理&#xff1b;0.2&#xff09;晚辈我 java.swing 烂到渣&#xff0c;没有写出干货荔枝&#xff0c;抱歉&#xff1b;【1】虚拟代理简述1&#xff09;远程代理&#xff1a;…

红黑树详细分析

转载自 coolblog 算法与数据结构“一、红黑树简介红黑树是一种自平衡的二叉查找树&#xff0c;是一种高效的查找树。它是由 Rudolf Bayer 于1972年发明&#xff0c;在当时被称为对称二叉 B 树(symmetric binary B-trees)。后来&#xff0c;在1978年被 Leo J. Guibas 和 Robert…

rest api如何创建_REST:创建资源

rest api如何创建资源创建是常见的REST API操作。 在这篇文章中&#xff0c;我们将看到如何创建单个资源。 客户要求 通常&#xff0c;通过将POST请求发送到父集合资源来创建资源。 这将使用新生成的ID创建一个新的下属资源。 例如&#xff0c;对/ projects的POST请求可用于在…

java字节码指令简介(仅了解)

【0】README0.1&#xff09;本文全文转自 “深入理解jvm”&#xff0c; 旨在了解 java字节码指令 的基础知识&#xff1b;【1】写在前面1&#xff09;由于jvm 采用面向操作数栈而不是寄存器的结构&#xff0c;所以大多数的指针都不包含操作数&#xff0c;只有一个操作码&#x…

什么是 CAS 机制

转载自 永远爱大家的 程序员小灰示例程序&#xff1a;启动两个线程&#xff0c;每个线程中让静态变量count循环累加100次。最终输出的count结果是什么呢&#xff1f;一定会是200吗&#xff1f;加了同步锁之后&#xff0c;count自增的操作变成了原子性操作&#xff0c;所以最终…

java xmpp_Java XMPP负载测试工具

java xmpp在本文中&#xff0c;我们将开发用Java编写的XMPP负载测试工具。 目录 1.简介 2. XMPP负载测试工具 3.先决条件 4. LoadXmppTest Java程序 4.1。 创建一个新的Maven项目 4.2。 创建主类 4.3。 XmppManager类 4.4。 建立 4.5。 负载测试 5.总结 6.参考 7.下载Maven项目…

jvm(7)-虚拟机类加载机制

【0】README0.1&#xff09;本文转自“深入理解jvm”&#xff0c;旨在学习 虚拟机类加载机制 的基础知识&#xff1b;【1】概述1&#xff09;类加载机制&#xff1a;虚拟机把描述类的数据从Class 文件加载到内存&#xff0c;并对数据进行校验&#xff0c;转换解析和初始化&…

什么是CAS机制?(进阶篇)

转载自 永远爱大家的 程序员小灰 这一期我们来深入介绍之前遗留的两个问题&#xff1a; Java当中CAS的底层实现 CAS的ABA问题和解决方法 首先看一看AtomicInteger当中常用的自增方法 incrementAndGet&#xff1a; public final int incrementAndGet() {for (;;) {int cur…

c++ 前缀 变量命名_前缀命名

c 前缀 变量命名如果您是第一次查看Takes或Cactoos的源代码&#xff0c;很可能会像其他命名约定一样被命名约定触发&#xff0c;这意味着大多数类名都有两个字母的前缀&#xff1a; BkSafe &#xff0c; RqFake &#xff0c; RsWithStatus &#xff0c; TkGzip等。 老实说&…

jvm(8)-虚拟机字节码执行引擎

【0】README0.1&#xff09;本文转自 “深入理解jvm”&#xff0c;旨在学习 虚拟机字节码执行引擎 的基础知识&#xff1b;【1】概述1&#xff09;物理机和虚拟机的执行引擎&#xff1a; 物理机的执行引擎是直接建立在处理器&#xff0c;硬件&#xff0c;指令集和操作系统层面上…

什么是大数据

转载自 玻璃猫 程序员小灰大数据是具有海量、高增长率和多样化的信息资产&#xff0c;它需要全新的处理模式来增强决策力、洞察发现力和流程优化能力。Big data is high volume, high velocity, and/or high variety information assets that require new forms of processing…

java 记录考勤记录_Java 14:记录

java 记录考勤记录Java 14是在几周前问世的&#xff0c;它引入了Record类型&#xff0c;它是一个不变的数据载体类&#xff0c;旨在容纳一组固定的字段。 请注意&#xff0c;这是一种预览语言功能 &#xff0c;这意味着必须使用--enable-preview标志在Java编译器和运行时中显式…

漫画:什么是HashMap

转载自 玻璃猫 程序员小灰众所周知&#xff0c;HashMap是一个用于存储Key-Value键值对的集合&#xff0c;每一个键值对也叫做Entry。这些个键值对&#xff08;Entry&#xff09;分散存储在一个数组当中&#xff0c;这个数组就是HashMap的主干。 HashMap数组每一个元素的初始值都…

jvm(10)-早期(编译期)优化

【0】README 0.1&#xff09;本文部分文字描述转自 “深入理解jvm”&#xff0c;旨在学习 早期&#xff08;编译期&#xff09;优化 的基础知识&#xff1b; 0.2&#xff09;本文部分文字描述转自&#xff1a; http://www.cnblogs.com/zhouyuqin/p/5223180.html 【1】概述 …

etl介绍与etl工具比较_ETL万岁

etl介绍与etl工具比较提取转换负载是从一个数据系统中提取数据并加载到另一个数据系统中的过程。 涉及的数据系统称为源系统和目标系统。 来自源系统的数据形状与目标系统不匹配&#xff0c;因此需要进行一些转换以使其兼容&#xff0c;该过程称为Transformation 。 转换是由m…

漫画:高并发下的HashMap

转载自 玻璃猫 程序员小灰上一期我们介绍了HashMap的基本原理&#xff0c; 这一期我们来讲解高并发环境下&#xff0c;HashMap可能出现的致命问题。HashMap的容量是有限的。当经过多次元素插入&#xff0c;使得HashMap达到一定饱和度时&#xff0c;Key映射位置发生冲突的几率会…