在树中找到最低共同祖先时出错

时间:2017-07-08 17:59:06

标签: c++ data-structures tree

我试图找到树中两个给定值的最低共同祖先。

我的方法是遍历树的左下角,检查各个节点的天气,它们下面都有节点。给出匹配的第一个节点是最低共同祖先。

有谁能告诉我这个功能的错误。

function loadDoc() {
        $.getJSON("/solutions" + , function(result, status, jqXHR) {
        var myList = (jqXHR.responseText);
        myList = JSON.parse(myList);
        var columns =[];
        columns = addAllColumnHeaders(myList);
        var table = document.getElementById("excelDataTable");
        var body = table.createTBody();
        for (var i = 0; i < myList.length; i++) {
            var row = body.insertRow();
            for (var colIndex = 0; colIndex < columns.length; colIndex++) {
              var cellValue = myList[i][columns[colIndex]];
              if (cellValue == null) cellValue = "";
              var cell = row.insertCell();
              cell.innerHTML = cellValue;
            }
          }
        });
    }


    function addAllColumnHeaders(myList) {
        $("#excelDataTable").html(""); 
        var columnSet = [];
        var table = document.getElementById("excelDataTable");
        var header = table.createTHead();
        var row = header.insertRow();
        for(var k in myList[0]) {
            if(k != "level"){
            columnSet.push(k);
            var cell = row.insertCell();
            cell.innerHTML = k;
            }
        }
        return columnSet;
    }

1 个答案:

答案 0 :(得分:1)

如果找到结果,您的递归函数应该只返回一个节点。如果找不到结果节点,它应该返回NULL。如果找到节点则中断,否则继续。我会这样做:

node * lca(node * root, int v1,int v2)   //to find the lowest common ancestor 
{
    if(root==NULL)
        return NULL;

    node* ans=NULL;

    // search the left child tree
    ans = lca(root->left,v1,v2); 
    if (ans != NULL)
      return ans; // if you found it you are finished

    // search the right child tree
    ans = lca(root->right,v1,v2);
    if (ans != NULL)
      return ans; // if you found it you are finished

    // test this tree node
    if( (find(root->left,v1)&&find(root->right,v2)) ||
        (find(root->left,v2)&&find(root->right,v1)))
    {
        // If the condition is true, this node is the result
        return root;
    }

    return NULL; // Neither this node nor any subordinate node of this node is the result 
}