N
N
neon45442021-10-31 20:54:00
PHP
neon4544, 2021-10-31 20:54:00

How to get the dates of all child objects of a binary tree?

here is the tree
R6IGg.png
Dump
rvNQ7.png
I try like this (getChil is already a piece of the tree if it is present in the tree with the given number.)

public function getChil($node)
    {

        if (!empty($node->data)){
            array_push($this->arr, $node->data);
        }

        if (!empty($node->left)){
            $this-> getChil($node->left);
        }

        if (!empty($node->right)){
            $this-> getChil($node->right);
        }

        return $this->arr;
    }


The bottom line is that I specify a digit, and if it is in the tree, it should return all child digits. My implementation returns only the digits of the left side, who can tell the problem? I will be sincerely grateful...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maksim Fedorov, 2021-10-31
@neon4544

You have the correct code:
sandbox.onlinephpfunctions.com/code/00ed97cf62c568...

<?php

class Node{
  private $arr = [];
  
  public function getChildren($node)
    {

        if (!empty($node->data)){
            array_push($this->arr, $node->data);
        }

        if (!empty($node->left)){
            $this->getChildren($node->left);
        }

        if (!empty($node->right)){
            $this->getChildren($node->right);
        }

        return $this->arr;
    }  
}

$node =  createNode(
    6 . '_base', 
    createNode(7 . '_right'),
    createNode(8 . '_left',
        createNode(81 . '_left'),
        createNode(82 . '_right',
           createNode(821 . '_right', 
                null,  
                createNode(824 . '_left') 
           )
          
        )
    )
);

function createNode($data, $right = null, $left = null) {
    $obj = new stdClass();
    $obj->data  = $data;
    $obj->right  = $right;
    $obj->left  = $left;
    return $obj;
}
    
var_dump((new Node)->getChildren($node));

// [
//  "6_base"
//  "8_left"
//  "82_right"
//  "821_right"
//  "824_left"
//  "81_left"
//  "7_right"
// ]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question