二叉树实战 22 题

二叉树实战 22 题,速度收藏吧!

技术小能手 2018-11-05 09:44:17 浏览40 评论0
</div>
        <ul class="tag-group">
                        <li class="tag tag-item">
                <a href="/tags/type_blog-tagid_1096/" class="label-item"><span>node</span></a>
            </li>
                        <li class="tag tag-item">
                <a href="/tags/type_blog-tagid_1143/" class="label-item"><span>ADD</span></a>
            </li>
                        <li class="tag tag-item">
                <a href="/tags/type_blog-tagid_2271/" class="label-item"><span>list</span></a>
            </li>
                        <li class="tag tag-item">
                <a href="/tags/type_blog-tagid_2570/" class="label-item"><span>arraylist</span></a>
            </li>
                </ul>


        <p class="blog-summary">
        <em>摘要:</em>

先上二叉树的数据结构:
class TreeNode{
   int val;
   //左孩子
   TreeNode left;
   //右孩子
   TreeNode right;
}
二叉树的题目普遍可以用递归和迭代的方式来解
1.

<div class="content-detail markdown-body">

f64d2e67023f836958cc9f1318042088c33382a9

先上二叉树的数据结构:

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;
   }

深刻的理解这些题的解法思路,在面试中的二叉树题目就应该没有什么问题,甚至可以怒他,哈哈。


原文发布时间为:2018-11-04

本文来自云栖社区合作伙伴“Java技术栈”,了解相关信息可以关注“Java技术栈”。

    <!-- 登录查看 begin -->
            <!-- 登录查看 end -->
</div>

    <div class="copyright-outer-line yq-blog-sem-remove">
                                    <div class="yq-blog-sem-remove copyright-notice">
            如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件至:yqgroup@service.aliyun.com 进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容。
        </div>
            </div>
                        <div class="yq-blog-sem-remove" style="margin-top: 20px;font-size: 12px;line-height: 1.8;color:#373d41;font-family:PingFangSC-Regular;word-break: break-all;">
            【云栖快讯】阿里云双11巅峰钜惠!组团拉新分200万红包,云主机仅99.5元!更可参与百团大战PK,抢百万现金!马上拼团!&nbsp;&nbsp;<a href="https://m.aliyun.com/act/team1111/#/" target="_blank" rel="nofollow">详情请点击</a>
        </div>
        
<div class="footer-detail yq-blog-sem-remove yq-blog-interaction clearfix">
    <a href="#comment" class="icon-pinglun comment_btn">评论  (<i>0</i>)</a>
    <span id="vote_btn" has_voted="" data-aid="664593" data-islogin="false" title="点赞" class="icon-zan opt-btn vote_btn ">点赞 (<span id="vote_num">0</span>)</span>
    <span id="mark_btn" has_marked="" data-aid="664593" data-islogin="false" title="收藏" class="icon-love opt-btn mark_btn ">收藏 (<span id="mark_num">0</span>)</span>
    <dl class="share-to">
        <dt>分享到:</dt>
        <dd>
            <a href="http://service.weibo.com/share/share.php?title=%E4%BA%8C%E5%8F%89%E6%A0%91%E5%AE%9E%E6%88%98+22+%E9%A2%98%EF%BC%8C%E9%80%9F%E5%BA%A6%E6%94%B6%E8%97%8F%E5%90%A7%EF%BC%81+%0A%0A%E5%85%88%E4%B8%8A%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%EF%BC%9A%0Aclass+TreeNode%7B%0A%C2%A0+%C2%A0int+val%3B%0A%C2%A0+%C2%A0%2F%2F%E5%B7%A6%E5%AD%A9%E5%AD%90%0A%C2%A0+%C2%A0TreeNode+left%3B%0A%C2%A0+%C2%A0%2F%2F%E5%8F%B3%E5%AD%A9%E5%AD%90%0A%C2%A0+%C2%A0TreeNode+right%3B%0A%7D%0A%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E9%A2%98%E7%9B%AE%E6%99%AE%E9%81%8D%E5%8F%AF%E4%BB%A5%E7%94%A8%E9%80%92%E5%BD%92%E5%92%8C%E8%BF%AD%E4%BB%A3%E7%9A%84%E6%96%B9%E5%BC%8F%E6%9D%A5%E8%A7%A3%0A1.&amp;url=https%3A%2F%2Fyq.aliyun.com%2Farticles%2F664593" target="_blank" class="icon-weibo"></a>
            <div class="wechat">
                <i class="icon-weixin"></i>
                <img src="/api/qrcode?size=140&amp;key=985b248ebf57b84c5619a6947d73598153db7c15&amp;text=https%3A%2F%2Fyq.aliyun.com%2Farticles%2F664593" alt="">
            </div>
        </dd>
    </dl>
</div>
<div class="yq-blog-pre-next yq-blog-sem-remove">
    <ul class="about-c-list">
                        <li><a href="/articles/664583">上一篇:【死磕 Spring】----- IOC 之 属性填充</a></li>
                                    <li><a href="/articles/664598">下一篇:搭建“双11”大型网站架构必须掌握的 5 个核心知识</a></li>
                </ul>
</div>
        <div class="yq-blog-related-articles yq-blog-sem-remove">
        <h3 class="title-info">相关文章</h3>
        <ul class="about-c-list">
                                <li>
                    <a href="/articles/631280">
                                                        nomasp 博客导读:Lisp/Emacs、Algor…
                                                </a>
                </li>
                                <li>
                    <a href="/articles/26089">
                                                        阿里电话面试之所做所得所感(2015年7月)
                                                </a>
                </li>
                                <li>
                    <a href="/articles/336881">
                                                        各大公司(Google,Microsoft,Baidu,…
                                                </a>
                </li>
                                <li>
                    <a href="/articles/40478">
                                                        数据结构与算法面试题80道
                                                </a>
                </li>
                                <li>
                    <a href="/articles/642728">
                                                        [剑指offer] JAVA版题解(全)
                                                </a>
                </li>
                                <li>
                    <a href="/articles/3710">
                                                        [程序员面试题精选100题]4.二叉树中和为某一值的所有…
                                                </a>
                </li>
                                <li>
                    <a href="/articles/8597">
                                                        算法面试题
                                                </a>
                </li>
                                <li>
                    <a href="/articles/334478">
                                                        微软等公司数据结构+算法面试100题
                                                </a>
                </li>
                                <li>
                    <a href="/articles/347895">
                                                        算法面试题总结
                                                </a>
                </li>
                                <li>
                    <a href="/articles/552086">
                                                        剑指Offer之重建二叉树(题6)
                                                </a>
                </li>
                        </ul>
    </div>
    <div class="yq-blog-comment yq-blog-sem-remove">
    <h3 class="title-info">网友评论</h3>
                <section class="comments-box clearfix">
            <div class="media-list comments" id="comments">
            <form accept-charset="UTF-8" action="/comments" method="POST" data-remote="true" data-target="#comments" class="js-comment-create js-active-on-valid css-unlogin">
                <input type="hidden" name="type" value="article">
                <input type="hidden" name="yunqi_csrf" value="YZIM5DJE4N">
                <input type="hidden" name="isCheck" value="1">
                <input type="hidden" name="pid" value="664593">

                <div class="form-group">
                    <div class="editor js-editor">
                                                        <div class="login_tips" id="comment">登录后可评论,请 <a id="fast_login" href="https://account.aliyun.com/login/login.htm?from_type=yqclub&amp;oauth_callback=https%3A%2F%2Fyq.aliyun.com%2Farticles%2F664593%3Fdo%3Dlogin" class="s4" hidefocus="true" rel="nofollow">登录</a> 或 <a href="https://account.aliyun.com/register/register.htm?from_type=yqclub&amp;oauth_callback=https%3A%2F%2Fyq.aliyun.com%2Farticles%2F664593%3Fdo%3Dlogin" target="_blank" class="s4" hidefocus="true" rel="nofollow">注册</a></div>
                                                </div><!-- /.editor  -->
                </div>


                <div class="form-group text-right">
                                                <a href="#modal-login" class="comment_button" data-toggle="modal">评论</a>
                                        </div>
            </form>
        </section>
        </div>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值