Nasıl bir ikili arama ağacında belirli bir anahtar değeri en yakın eleman bulmak için?

oy
15

Bir şey eksik o anahtara en yakın düğüm bulurum nasıl anahtarları olarak tamsayı değerlere sahip bir BST Verilen? TSİ düğüm nesne (Java) kullanılarak temsil edilmektedir. En yakın ör 4,5,9 olacak ve anahtar 6 ise o 5 dönecektir ..

Oluştur 02/06/2011 saat 01:50
kaynak kullanıcı
Diğer dillerde...                            


11 cevaplar

oy
-1

En kolay çözüm ne zamandan beri ağacınızı Recurse olduğunu

  • Eğer eleman bulmak
  • Bir yaprak ulaşır. Bu dava size en yakın değeri yaprak veya yaprak üstüdür eğer karşılaştırma birkaç belirlemek için yapmalıdır.

uygulama Sana bağlı.

Cevap 02/06/2011 saat 02:02
kaynak kullanıcı

oy
18

Ağacın Traverse gibi eleman bulmak için olur. O rekor anahtarınız en yakın olan değer yapmak iken. Şimdi ne zaman kendisini kaydedilen değer döndürmek anahtar için bir düğüm bulamadık.

Eğer anahtarın aradığını Yani 3şu ağaçta sen düğümde sona ereceğini 6bir maç bulmadan ancak kaydedilen değer olacaktır 2bu tüm uçtan bir uca geçen düğümler (en yakın anahtar olduğu için 2, 7, 6).

                 2
              1      7
                   6   8
Cevap 02/06/2011 saat 02:03
kaynak kullanıcı

oy
11

Traverse O (n) bir zaman alır. biz üst alt ilerleyebilir mi? Bu özyinelemeli kodu gibi:

Tnode * closestBST(Tnode * root, int val){
    if(root->val == val)
        return root;
    if(val < root->val){
        if(!root->left)
            return root;
        Tnode * p = closestBST(root->left, val);
        return abs(p->val-val) > abs(root->val-val) ? root : p;
    }else{
        if(!root->right)
            return root;
        Tnode * p = closestBST(root->right, val);
        return abs(p->val-val) > abs(root->val-val) ? root : p;
    }   
    return null;
}
Cevap 08/06/2011 saat 09:41
kaynak kullanıcı

oy
8

Bu O'da çözülebilir zaman (* n * log).

  • Bir düğüm değeri belirli bir değeri ile aynı ise, yakın düğümün;
  • Bir düğüm değeri belirli bir değerden daha büyük ise, sol çocuğa hareket ettirmek;
  • Bir düğüm değeri verilen değerden daha az ise, sağ çocuğa taşıyın.

Algoritma aşağıdaki C ++ kodu ile gerçekleştirilebilir:

BinaryTreeNode* getClosestNode(BinaryTreeNode* pRoot, int value)
{
    BinaryTreeNode* pClosest = NULL;
    int minDistance = 0x7FFFFFFF;
    BinaryTreeNode* pNode = pRoot;
    while(pNode != NULL){
        int distance = abs(pNode->m_nValue - value);
        if(distance < minDistance){
            minDistance = distance;
            pClosest = pNode;
        }

        if(distance == 0)
            break;

        if(pNode->m_nValue > value)
            pNode = pNode->m_pLeft;
        else if(pNode->m_nValue < value)
            pNode = pNode->m_pRight;
    }

    return pClosest;
}

Sen ziyaret edebilirsiniz blogumu fazla ayrıntı için.

Cevap 14/03/2013 saat 03:19
kaynak kullanıcı

oy
0

Bu Kuyruk ve ArrayList kullanılarak yapılabilir. Kuyruk ağaç üzerinde bir genişlik ilk arama gerçekleştirmek için kullanılacaktır. ArrayList Genişlik ilk sırada ağacın elemanı saklamak için kullanılacaktır. İşte aynı uygulamaya koddur

Queue queue = new LinkedList();
ArrayList list = new ArrayList();
int i =0;
public Node findNextRightNode(Node root,int key)
{
    System.out.print("The breadth first search on Tree : \t");      
    if(root == null)
        return null;

    queue.clear();
    queue.add(root);

    while(!queue.isEmpty() )
    {
        Node node = (Node)queue.remove();
        System.out.print(node.data + " ");
        list.add(node);
        if(node.left != null) queue.add(node.left);
        if(node.right !=null) queue.add(node.right);            
    }

    Iterator iter = list.iterator();
    while(iter.hasNext())
        {
            if(((Node)iter.next()).data == key)
            {
                return ((Node)iter.next());
            }               
        }

    return null;
}
Cevap 15/01/2014 saat 14:06
kaynak kullanıcı

oy
2

yaklaşımdaki sorun elemanları BST oluşturmak için girilen edildiği dizisi üzerinde gelmesiyle değil "doğru geçişi ve en yakın bulmakta sol". Biz TSİ dizisi 22, 15, 16, 6,14,3,1,90 için 11 arama, doğru yanıt tek yöntem tüm düğümler çapraz özyinelemeye kullanıyor olmalıdır 14. iken, yukarıdaki yöntem, 15 döndürür özyinelemeli fonksiyonun sonucunda en yakın olanı döndürerek. Bu bize en yakın değeri vereceğiz

Cevap 02/06/2014 saat 18:02
kaynak kullanıcı

oy
9

İşte Python bir özyinelemeli çözüm:

def searchForClosestNodeHelper(root, val, closestNode):
    if root is None:
        return closestNode

    if root.val == val:
        return root

    if closestNode is None or abs(root.val - val) < abs(closestNode.val - val):
        closestNode = root

    if val < root.val:
        return searchForClosestNodeHelper(root.left, val, closestNode)
    else:
        return searchForClosestNodeHelper(root.right, val, closestNode)

def searchForClosestNode(root, val):
    return searchForClosestNodeHelper(root, val, None)
Cevap 21/06/2014 saat 23:44
kaynak kullanıcı

oy
0
void closestNode(Node root, int k , Node result) {
    if(root == null) 
    {
       return;      //currently result is null , so it  will be the result
    }
    if(result == null || Math.abs(root.data - k) < Math.abs(result.data - k) )
    {
      result == root;
    }
    if(k < root.data)
    {
    closestNode(root.left, k, result)
    } 
    else 
    {
        closestNode(root.right, k, result);
    }

}
Cevap 24/07/2016 saat 05:45
kaynak kullanıcı

oy
0

biri ben farklı örneklerle çalışır görebilirsiniz.

public Node findNearest(Node root, int k) {
    if (root == null) {
        return null;
    }
    int minDiff = 0;
    Node minAt = root;
    minDiff = Math.abs(k - root.data);

    while (root != null) {
        if (k == root.data) {
            return root;
        }
        if (k < root.data) {
            minAt = updateMin(root, k, minDiff, minAt);
            root = root.left;
        } else if (k > root.data) {
            minAt = updateMin(root, k, minDiff, minAt);
            root = root.right;
        }

    }
    return minAt;
}

private Node updateMin(Node root, int k, int minDiff, Node minAt) {
    int curDif;
    curDif = Math.abs(k - root.data);
    if (curDif < minDiff) {
        minAt = root;
    }
    return minAt;
}
Cevap 04/02/2017 saat 10:10
kaynak kullanıcı

oy
0

İşte BST en yakın eleman bulmak için tam bir Java kodudur.

        package binarytree;

        class BSTNode {
            BSTNode left,right;
            int data;

            public BSTNode(int data) {
                this.data = data;
                this.left = this.right = null;
            }
        }

        class BST {
            BSTNode root;

            public static BST createBST() {
                BST bst = new BST();
                bst.root = new BSTNode(9);
                bst.root.left = new BSTNode(4);
                bst.root.right = new BSTNode(17);

                bst.root.left.left = new BSTNode(3);
                bst.root.left.right= new BSTNode(6);

                bst.root.left.right.left= new BSTNode(5);
                bst.root.left.right.right= new BSTNode(7);

                bst.root.right.right = new BSTNode(22);
                bst.root.right.right.left = new BSTNode(20);

                return bst;
            }
        }

        public class ClosestElementInBST {
            public static void main(String[] args) {
                BST bst = BST.createBST();
                int target = 18;
                BSTNode currentClosest = null;
                BSTNode closestNode = findClosestElement(bst.root, target, currentClosest);

                if(closestNode != null) {
                    System.out.println("Found closest node: " + closestNode.data);
                }
                else {
                    System.out.println("Couldn't find closest node.");
                }
            }

            private static BSTNode findClosestElement(BSTNode node, int target, BSTNode currentClosest) {
                if(node == null) return currentClosest;

                if(currentClosest == null || 
                        (currentClosest != null && (Math.abs(currentClosest.data - target) > Math.abs(node.data - target)))) {
                    currentClosest = node;
                }

               if(node.data == target) return node;

                else if(target < node.data) {
                    return findClosestElement(node.left, target, currentClosest);
                }

                else { //target > node.data
                    currentClosest = node;
                    return findClosestElement(node.right, target, currentClosest);
                }
            }

        }
Cevap 11/06/2018 saat 20:33
kaynak kullanıcı

oy
0

Burada en az bir fark depolamak için BST ve ek tamsayı özelliklerini kullanır Java çalışma çözümdür

public class ClosestValueBinaryTree {
        static int closestValue;

        public static void closestValueBST(Node22 node, int target) {
            if (node == null) {
                return;
            }
            if (node.data - target == 0) {
                closestValue = node.data;
                return;
            }
            if (Math.abs(node.data - target) < Math.abs(closestValue - target)) {
                closestValue = node.data;
            }
            if (node.data - target < 0) {
                closestValueBST(node.right, target);
            } else {
                closestValueBST(node.left, target);
            }
        }
    }

Çalışma zamanı karmaşıklığı - O (logn)

Uzay Zaman karmaşıklığı - O (1)

Cevap 08/09/2018 saat 18:23
kaynak kullanıcı

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more