94. Binary Tree Inorder Traversal

二元樹中序遍歷,由左至右,中間輸出

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     public $val = null;
 *     public $left = null;
 *     public $right = null;
 *     function __construct($val = 0, $left = null, $right = null) {
 *         $this->val = $val;
 *         $this->left = $left;
 *         $this->right = $right;
 *     }
 * }
 */
class Solution {

    private $result = [];
    /**
     * @param TreeNode $root
     * @return Integer[]
     */
    function inorderTraversal($root) {
        $this->traversal($root);

        return $this->result;
    }

    function traversal($node) {
        if ($node === null){
            return;
        }

        $this->traversal($node->left);
        $this->result[] = $node->val;
        $this->traversal($node->right);
    }
}

Last updated