zoukankan      html  css  js  c++  java
  • 17.寻找下一个结点

    题目描述

    请设计一个算法,寻找二叉树中指定结点的下一个结点(即中序遍历的后继)。

    给定树的根结点指针TreeNode* root和结点的值int p,请返回值为p的结点的后继结点的值。保证结点的值大于等于零小于等于100000且没有重复值,若不存在后继返回-1。

    思路:中序遍历,将节点存入队列,对队列操作

    代码如下:

    import java.util.*;
    
    /*
    public class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;
        public TreeNode(int val) {
            this.val = val;
        }
    }*/
    public class Successor {
        Queue<TreeNode> q=new LinkedList<TreeNode>();
        
        public int findSucc(TreeNode root, int p) {
            if(root==null)return -1;
           InOrder(root);
            int tmp=-1;
            while(!q.isEmpty()){
                tmp=q.poll().val;
                if(tmp==p){
                    if(!q.isEmpty()){
                        return q.poll().val;
                     }else{
                        return -1;
                    }
                }
            }
            return -1;
        }
        public void InOrder(TreeNode root){
            if(root.left!=null)
                 InOrder(root.left);
            if(root!=null){
                q.offer(root);
            }
            if(root.right!=null)
                InOrder(root.right);
        }
    }
    

      

  • 相关阅读:
    移动web性能优化从入门到进阶
    授权保存到相册
    授权通讯地址
    windows putty 链接到 linux 免密码
    my docker note
    docker run -i -t --rm
    Command Not Found
    firewall-cmd 笔记
    vim 插件 Tabularize
    vim :find
  • 原文地址:https://www.cnblogs.com/mlz-2019/p/4794608.html
Copyright © 2011-2022 走看看