微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在二叉树中有效地找到路径?

如何解决如何在二叉树中有效地找到路径?

我正在尝试找到两个节点之间的路径。

它可以是从根节点到其他节点或只是从其他节点到其他节点。我面临的问题是时间超过了我测试代码的时间。找到路径花了很长时间。

class Node{
      int key; string name; Node* lChild; Node* rChild;
}

这是我的寻路函数

void findpath(string x,string y){ 
      int xKey = findKey(x); // custom function to find the key to move left and right
      int yKey = findKey(y);
      Node* lca = LCA(head,xKey,yKey); // this will find the lca and head node is the just the root node.
      while(true){ // loop through to the left; }
      while(true){ // loop through to the right; }
}

找到 lca 后,我从左到右循环。但是自从我使用两个 while 循环以来,它花了很长时间。如何降低此查找路径的时间复杂度?

这是我的树照片:

Tree

预期输出

findpath(D,F) --> D,B,A,C,F 

findpath(A,I) --> A,G,I

findpath(F,E) --> F,D,E

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。