日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode 2096. 从二叉树一个节点到另一个节点每一步的方向(最小公共祖先)

發布時間:2024/7/5 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LeetCode 2096. 从二叉树一个节点到另一个节点每一步的方向(最小公共祖先) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

    • 1. 題目
    • 2. 解題

1. 題目

給你一棵 二叉樹 的根節點 root ,這棵二叉樹總共有 n 個節點。
每個節點的值為 1 到 n 中的一個整數,且互不相同
給你一個整數 startValue ,表示起點節點 s 的值,和另一個不同的整數 destValue ,表示終點節點 t 的值。

請找到從節點 s 到節點 t 的 最短路徑 ,并以字符串的形式返回每一步的方向。
每一步用 大寫 字母 ‘L’ ,‘R’ 和 ‘U’ 分別表示一種方向:

  • 'L' 表示從一個節點前往它的 左孩子 節點。
  • 'R' 表示從一個節點前往它的 右孩子 節點。
  • 'U' 表示從一個節點前往它的 節點。

請你返回從 s 到 t 最短路徑 每一步的方向。

示例 1:

輸入:root = [5,1,2,3,null,6,4], startValue = 3, destValue = 6 輸出:"UURL" 解釋:最短路徑為:31526

示例 2:

輸入:root = [2,1], startValue = 2, destValue = 1 輸出:"L" 解釋:最短路徑為:21 。提示: 樹中節點數目為 n 。 2 <= n <= 10^5 1 <= Node.val <= n 樹中所有節點的值 互不相同 。 1 <= startValue, destValue <= n startValue != destValue

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。

2. 解題

  • 先求解兩個點的最小公共祖先 p
  • 然后 dfs1 求解 p 到 start 的步數 x,得到答案有 x 個 U
  • 再 dfs2 求解 p 到 end 的路徑,就是答案的 后半部分
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode() : val(0), left(nullptr), right(nullptr) {}* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}* };*/ class Solution {int stepdowntofindstart = -1;bool finddest = false;string pathtodest, path; public:string getDirections(TreeNode* root, int startValue, int destValue) {TreeNode* p = lowestcommonParent(root, startValue, destValue);dfs1(p, startValue, 0);dfs2(p, destValue);if(stepdowntofindstart)return string(stepdowntofindstart, 'U') + pathtodest;return pathtodest;}TreeNode* lowestcommonParent(TreeNode* root, int sv, int dv){ // 最小公共祖先if(!root) return root;if(root->val == sv || root->val == dv)return root;auto l = lowestcommonParent(root->left, sv, dv);auto r = lowestcommonParent(root->right, sv, dv);if(l && r) return root;return l ? l : r;}void dfs1(TreeNode* root, int sv, int step){ // 最小祖先到 start 的步數if(stepdowntofindstart != -1 || !root) return;if(root->val == sv){stepdowntofindstart = step;return;}dfs1(root->left, sv, step+1);dfs1(root->right, sv, step+1);}void dfs2(TreeNode* root, int dv){ // 最小祖先到 end 的路徑 pathif(finddest || !root) return;if(root->val == dv){finddest = true;pathtodest = path;return;}path.push_back('L');dfs2(root->left, dv);path.pop_back();path.push_back('R');dfs2(root->right, dv);path.pop_back();} };

164 ms 111.3 MB C++


我的CSDN博客地址 https://michael.blog.csdn.net/

長按或掃碼關注我的公眾號(Michael阿明),一起加油、一起學習進步!

創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

總結

以上是生活随笔為你收集整理的LeetCode 2096. 从二叉树一个节点到另一个节点每一步的方向(最小公共祖先)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。