MediumGoogle,Amazon,Microsoft,Tiktokhttps://leetcode.com/problems...方法一,BFS两次,第一遍构造父表,同时定位起始节点和结束节点,第二遍从起始节点BFS开始寻找结束节点,同时保存路径。该方法超时。类Pair{TreeNode节点;字符串路径;publicPair(TreeNodenode,Stringpath){this.node=node;this.path=路径;}}classSolution{publicStringgetDirections(TreeNoderoot,intstartValue,intdestValue){Mapparent=newHashMap<>();parent.put(root,null);Queueq=newLinkedList<>();q.offer(根);TreeNodestart=null,end=null;while(!q.isEmpty()){TreeNodecur=q.poll();如果(cur.val==startValue)开始=cur;如果(cur.val==destValue)end=cur;如果(cur.left!=null){parent.put(cur.left,cur);q.offer(cur.left);}if(cur.right!=null){parent.put(cur.right,cur);q.offer(cur.right);}}队列queue=newLinkedList<>();阙ue.offer(新对(开始,“”));while(!queue.isEmpty()){Paircur=queue.poll();if(cur.node==end)returncur.path;TreeNodeparentNode=parent.get(cur.node);如果(parentNode!=null)queue.offer(newPair(parentNode,cur.path+"U"));树节点leftNode=cur.node.left;如果(leftNode!=null)queue.offer(newPair(leftNode,cur.path+"L"));TreeNoderightNode=cur.node.right;如果(rightNode!=null)queue.offer(newPair(rightNode,cur.path+"R"));}返回空值;}}方法二,结合三个小算法,LCA寻找最低公共祖先,找到一个节点到另一个节点的路径,构造总路径类TreeNode{TreeNode左,右;整数值;publicTreeNode(intval){this.val=val;}}publicclassLC2096{publicStringgetDirections(TreeNoderoot,intstart,intend){//找到lcaTreeNodelca=lca(root,start,end);//分别构造从LCA到起点和LCA到终点的路径ListpathFromLcaToStart=newArrayList<>();ListpathFromLcaToEnd=newArrayList<>();buildPath(lca,开始,pathFromLcaToStart);buildPath(lca,结束,pathFromLcaToEnd);StringBuilderres=newStringBuilder();//合并总路径,LCA-start需要一路往回走,都是Ures.append("U".repeat(pathFromLcaToStart.size()));for(charcharacter:pathFromLcaToEnd)res.append(character);返回res.toString();}privatebooleanbuildPath(TreeNodenode,inttarget,Listpath){if(node==null)returnfalse;if(node.val==target)返回真;if(node.left!=null){path.add('L');如果(buildPath(node.left,target,path))返回true;path.remove(path.size()-1);}if(node.right!=null){path.add('R');如果(buildPath(node.right,target,path))返回true;path.remove(path.size()-1);}返回假;}privateTreeNodelca(TreeNoderoot,intstart,intend){if(root==null||root.val==start||root.val==end)returnroot;TreeNodeleft=lca(root.left,start,end);TreeNoderight=lca(root.right,start,end);如果(左!=空&&右!=空)返回根;向左返回!=null?左右;}}