js 이진 트리 쿼리 순회, 삽입 및 뒤집기에 대한 코드

不言
풀어 주다: 2018-07-14 17:27:28
원래의
1825명이 탐색했습니다.

이 기사에서는 주로 js 바이너리 트리 쿼리 탐색, 삽입 및 뒤집기에 대한 코드를 소개합니다. 이제 특정 참조 값이 있으므로 필요한 친구가 참조할 수 있습니다.

function BST(){
        this.root = null
        this.insert = insert
        this.find = find
        this.mirror = mirror;
        
    }
    function Node(data,left,right){
        this.data = data
        this.left = left
        this.right = right
        this.show = show
    }
    function show() {
       return this.data;
    }
    function mirror(root){
        if(root == null){
            return
        }
        if(root.left == null && root.right == null){
            return
        }
        let temp = root.left;
        root.left = root.right;
        root.right = temp;
        mirror(root.left)
        mirror(root.right)
    }
    function insert(data){
        var n = new Node(data,null,null)
        if(this.root == null){
            this.root = n
        }else{
            var current = this.root
            while(true){
                if(data < current.data){
                    if(current.left == null){
                        current.left = n
                        break
                    }
                    current = current.left
                }else{
                    if(current.right == null){
                        current.right = n
                        break
                    }
                    current = current.right
                }
            }
        }
    }
    function find(data){
        var current = this.root
        while(true){
            if(data == current.data){
                return current
            }
            current = data < current.data ? current.left : current.right
            if(current == null){
                return null
            }
        }
    }
    function inorder(node){
        if(!(node == null)){
            inorder(node.left)
            console.log(node.show())
            inorder(node.right)
        }
    }
    var nums = new BST()
    nums.insert(23)
    nums.insert(22)
    nums.insert(16)
    nums.insert(5)
    nums.insert(3)
    nums.insert(99)
    nums.insert(22)
    inorder(nums.root)  
    mirror(nums.root)
    console.log(nums.root)
로그인 후 복사

매우 간단하고 완료되었습니다.

위 내용은 이 글의 전체 내용입니다. 모든 분들의 학습에 도움이 되었으면 좋겠습니다. 더 많은 관련 내용은 PHP 중국어 홈페이지를 주목해주세요!

관련 추천:

js의 템플릿 메소드 패턴에 대한 설명

Font Awesome을 사용하여 Vue.js를 통해 작은 아이콘을 구현하는 방법

js 배열 필터 사용에 대해

위 내용은 js 이진 트리 쿼리 순회, 삽입 및 뒤집기에 대한 코드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!