《leetcode-php》根据先序遍历和后序遍历构造二叉树

给出一棵树的前序遍历和中序遍历,请构造这颗二叉树 
注意: 可以假设树中不存在重复的节点 
Given preorder and inorder traversal of a tree, construct the binary tree. 
Note: You may assume that duplicates do not exist in the tree.

val = $val;
    }
}
function buildTree($arrPreOrder, $arrPostOrder) {
    if (empty($arrPreOrder) || empty($arrPostOrder)) {
        return null;
    }
    $node = getNode($arrPreOrder, 0, count($arrPreOrder) - 1, $arrPostOrder, 0, count($arrPostOrder) - 1);
    return $node;
}
function getNode($arrPreOrder, $x1, $y1, $arrPostOrder, $x2, $y2) {
    print "$x1 $y1 $x2 $y2\n";
    if ($x1 > $y1 || $x2 > $y2 || $y1 > count($arrPreOrder) || $y2 > count($arrPostOrder)) {
        return;
    }
    $node = new Node($arrPreOrder[$x1]);
    for ($i = $x2; $i <= $y2; $i ++) {
        if ($arrPostOrder[$i] == $arrPreOrder[$x1 + 1]) {
            //后序遍历的位置$i,可以确定先序遍历的偏移量为$i - $x2
            $node->left = getNode($arrPreOrder, $x1 + 1, $x1 + $i - $x2 + 1, $arrPostOrder, $x2, $i);
            $node->right = getNode($arrPreOrder, $x1 + $i - $x2 + 2, $y1, $arrPostOrder, $i + 1 , $y2 - 1);
            break;
        }
    }
    return $node;
}
$arrPreOrder = [1, 2, 4, 6, 3, 5];
$arrPostOrder = [4,6,2,5,3,1];
$node = buildTree($arrPreOrder, $arrPostOrder);
output($node);
function output($node) {
    print $node->val."\t";
    print "左".$node->left->val."右".$node->right->val."\n";
    if ($node->left != null) {
        output($node->left);
    }
    if ($node->right != null) {
        output($node->right);
    }
    print "\n";
}

 

你可能感兴趣的:(leetCode-php)