这是二叉树路径问题: 给定二叉树,返回所有根到叶路径。
例如,给定以下二叉树:
1
/ \
2 3
\
5
所有根到叶的路径都是:
["1->2->5", "1->3"]
这是我的Javascript代码:
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {string[]}
*/
var binaryTreePaths = function(root) {
var paths = [];
if(!root) return [];
if(root.left == null && root.right == null){
if(paths.length == 0) return [""+root.val];
else return root.val;
}
else{
if(root.left) paths.push(root.val + "->" + binaryTreePaths(root.left))
if(root.right) paths.push(root.val + "->" + binaryTreePaths(root.right))
}
return paths;
};
测试用例:
输入:
[1,2,3,5,6]
输出:
["1->2->5,2->6","1->3"]
预期:
["1->2->5","1->2->6","1->3"]
为什么我的代码输出没有返回“1-> 2-> 6”的完整路径?
答案 0 :(得分:4)
进行递归调用时,函数将返回一个数组。你不能只用前缀字符串推送该数组的串联;你需要迭代每个返回的子路径并构建一个单独的路径来推送到数组:
//Rotate the character relative to the camera direction
if (attackTimer <= 0 && moveDirection != Vector3.zero)
{
var targetDirection = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
targetDirection = Camera.main.transform.TransformDirection(targetDirection);
targetDirection.y = 0.0f;
Quaternion targetRotation = Quaternion.LookRotation(targetDirection, Vector3.up);
float rotationSpeed = 100.0f;
Quaternion newRotation = Quaternion.Lerp(rbody.rotation, targetRotation, rotationSpeed * Time.deltaTime);
//Apply the rotation
rbody.MoveRotation(newRotation);
}
//Move the character
if (IsMoving == true)
{
if (Input.GetAxis("Vertical") != 0) //Vertical movement (Up/Down)
{
if (attackTimer <= 0 || !IsGrounded)
{
rbody.AddForce(transform.forward * speed);
}
}