You are given the root
of a binary tree with n
nodes. Each node is uniquely assigned a value from 1
to n
. You are also given an integer startValue
representing the value of the start node s
, and a different integer destValue
representing the value of the destination node t
.
Find the shortest path starting from node s
and ending at node t
. Generate step-by-step directions of such path as a string consisting of only the uppercase letters 'L'
, 'R'
, and 'U'
. Each letter indicates a specific direction:
'L'
means to go from a node to its left child node.'R'
means to go from a node to its right child node.'U'
means to go from a node to its parent node.
Return the step-by-step directions of the shortest path from node s
to node t
.
Example 1:
Input: root = [5,1,2,3,null,6,4], startValue = 3, destValue = 6 Output: "UURL" Explanation: The shortest path is: 3 → 1 → 5 → 2 → 6.
思路:首先找到LCA,然后收集path list,是走左还是走右的path,然后左边的path全部变成 U, 右边的串起来就是答案,这个题目很好的是LCA的包装,而且也考察了DFS;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public String getDirections(TreeNode root, int startValue, int destValue) {
TreeNode LCA = findLCA(root, startValue, destValue);
LinkedList<String> slist = new LinkedList<>();
dfs(LCA, slist, startValue);
LinkedList<String> dlist = new LinkedList<>();
dfs(LCA, dlist, destValue);
StringBuilder sb = new StringBuilder();
for(int i = 0; i < slist.size(); i++) {
sb.append("U");
}
while(!dlist.isEmpty()) {
sb.append(dlist.poll());
}
return sb.toString();
}
private boolean dfs(TreeNode node, LinkedList<String> list, int target) {
if(node == null) {
return false;
}
if(node.val == target) {
return true;
}
// move to left;
list.add("L");
if(dfs(node.left, list, target)) {
return true;
}
list.removeLast();
// move to right;
list.add("R");
if(dfs(node.right, list, target)) {
return true;
}
list.removeLast();
return false;
}
private TreeNode findLCA(TreeNode root, int s, int e) {
if(root == null) {
return null;
}
if(root.val == s || root.val == e) {
return root;
}
TreeNode leftnode = findLCA(root.left, s, e);
TreeNode rightnode = findLCA(root.right, s, e);
if(leftnode != null && rightnode != null) {
return root;
} else if(leftnode == null) {
return rightnode;
} else {
return leftnode;
}
}
}