二叉树前序遍历 中序遍历 后续遍历 算法实现

来源:互联网 发布:知乎女朋友是校花 编辑:程序博客网 时间:2024/05/16 18:46

掌握以下概念是必要的:

前序遍历: 

    1.访问根节点 
    2.前序遍历左子树 
    3.前序遍历右子树 
中序遍历: 
    1.中序遍历左子树 
    2.访问根节点 
    3.中序遍历右子树 
后序遍历: 
    1.后序遍历左子树 

    2.后序遍历右子树 

    3.访问根节点


class BinaryTree {    var $left = null;    var $right= null;    var $value= 0;    function __construct($value) {        $this->value= $value;    }}

  $b1 = new BinaryTree(4);$b2 = new BinaryTree(6);$b3 = new BinaryTree(8);$b4 = new BinaryTree(10);$b5 = new BinaryTree(12);$b6 = new BinaryTree(14);$b7 = new BinaryTree(16);  $b4->left = $b2;$b4->right= $b6;  $b2->left = $b1;$b2->right= $b3;  $b6->left = $b5;$b6->right= $b7;function prePrint($node) {    if($node == null){        return ;    }    print($node->value);echo "\n";    preprint($node->left);    preprint($node->right);}prePrint($b4);echo "\n";function midPrint($node) {    if($node == null){        return ;    }    midPrint($node->left);    print($node->value);echo "\n";    midPrint($node->right);}midPrint($b4);echo "\n";function rightPrint($node) {    if($node == null){        return ;    }    rightPrint($node->left);    rightPrint($node->right);    print($node->value);echo "\n";}rightPrint($b4);