通过二叉树查找最大总和路径 - javascript

时间:2016-07-21 22:23:43

标签: javascript binary-search-tree

我一直试图解决这个问题几天,并且似乎无法优化解决方案以使其成为可行的。

我有一棵100级深的树,所以蛮力(2 ^ 100种可能的组合?)显然不起作用..

这是我到目前为止的代码:

// Node constructor | structure of nodes
var Node = function(val) {
  this.val = Number(val);
  this.left = null;
  this.right = null;
}

function maxPathUtil(top, store) {
  if (top === null || top === undefined) return 0;
  if (top.left === null && top.right === null) {
    // console.log("hello");
    return top.val;
  }

  leftSub = maxPathUtil(top.left, store);
  rightSub = maxPathUtil(top.right, store);
  store[0] = Math.max(store[0], leftSub+rightSub+top.val);

  return Math.max(leftSub, rightSub) + top.val;
}

function maxPathSum(top) {
  store = [];
  store[0] = 0;
  maxPathUtil(top, store)
  return store[0];
}

var top = nodify(levels);
console.log(maxPathSum(top));

有没有办法记住这个解决方案/以其他方式改进大O或者是否有效率?

3 个答案:

答案 0 :(得分:0)

因此,每个节点都应该有额外的额外属性,让我们称之为" currLength"

解析文本文件并将节点添加到树中时,需要将此值设置为父节点的currLength +当前节点的值。

在此之后,您只需要检查树的底部节点以获取每条路径的长度。

如果你想进一步优化它,那么你可以将一个currMaxLength变量添加到树中,最初将它设置为-Infinity,当你添加一个currLength更高的节点时,你可以将currMaxLength设置为currLength。

请记住,这并没有使它更快,这只是将compexity移动到init部分。它就像插入排序一样。

答案 1 :(得分:0)

这是我如何用JavaScript解决此问题的方法,希望对您有所帮助!

var hasPathSum = function(root, sum) {
    if (root == null) {
        return false
    }
    var result = checkTree(root,root.val,sum)
    console.log(result)
    return result 
};

function checkTree(node,currentSum,sum) {
    if (currentSum == sum && node.left == null && node.right == null) {
        return true
    }
    var result = false
    if (node.left != null) {
        result = result || checkTree(node.left,currentSum+node.left.val,sum)
    }
    if (node.right != null) {
        result = result || checkTree(node.right,currentSum+node.right.val,sum)
    }
    return result
}

也在my Github

答案 2 :(得分:0)

function pathSum(root , sum){
      //Add Base Case For Recursion
      
      if(root === null)return false;
      
      //Add another base case 
      if(root.val === sum &&(root.left === null && root.right === null)return true
    
 // here when it reach to the leaf where the next is null for both left and right

      return pathSum(root.left , sum - root.val)|| pathSum(root.right ,sum - root.val )
      
      //So In the code above I added (||) because If the first recursion return false, it will execute next recursion and so on 
    }