Javascript樹(一):廣度遍歷和深度遍歷

文章關鍵點

1. 樹的建立

2. 深度遍歷和廣度遍歷

3.callback回調函數

4. 遍歷方式查找添加刪除等接口

1.樹的建立

一個節點有三個部分組成

  • data 存儲數據
  • parent 指向的父節點
  • children 孩子節點
function Node(data){
  this.data = data;
  this.parent = null;
  this.children = [ ];
}

function Tree(node){
  var node = new Node(data);
  this._root = node;
}

var tree = new Tree('CEO'); 
// {data: 'CEO', parent: null, children: []}
tree._root;

2.(a) 深度遍歷(DSF)

Tree.prototype.traverseDF = function (callback) {  
        (function recurse(currentNode) {  
            for(let i=0;i<currentNode.children.length;i++){
                recurse(currentNode.children[i]);
            }
            callback(currentNode);
        })(this._root);
    }

eg:

var tree = new Tree('one');

tree._root.children.push(new Node('two'));
tree._root.children[0].parent = tree;

tree._root.children.push(new Node('three'));
tree._root.children[1].parent = tree;

tree._root.children.push(new Node('four'));
tree._root.children[2].parent = tree;

tree._root.children[0].children.push(new Node('five'));
tree._root.children[0].children[0].parent = tree._root.children[0];

tree._root.children[0].children.push(new Node('six'));
tree._root.children[0].children[1].parent = tree._root.children[0];

tree._root.children[2].children.push(new Node('seven'));
tree._root.children[2].children[0].parent = tree._root.children[2];

/*

creates this tree

 one
 ├── two
 │   ├── five
 │   └── six
 ├── three
 └── four
     └── seven

*/

2.(b)廣度遍歷(利用queue)

    Tree.prototype.traverseBF = function (callback) {
        var queue = new Queue();
        queue.enqueue(this._root);
        var currentTree = queue.dequeue();
        while(currentTree){
            for(let i =0;i<currentTree.children.length;i++){
                queue.enqueue(currentTree.children[i]);
            }
            callback(currentTree);
            currentTree = queue.dequeue();
        }
      }

callback
默認為一個函數,使得在函數內能調用其它函數

tree.traverseDF(function(node) {
        console.log(node.data)
    });

    /*
     
    logs the following strings to the console
     
    'five'
    'six'
    'two'
    'three'
    'seven'
    'four'
    'one'
     
    */
  1. 遍歷方式查找添加刪除等接口
a.遍歷方式
Tree.prototype.contains = function (callback,traversal) { 
        traversal.call(this,callback);
     }

eg:

//tree is an example of a root node
tree.contains(function(node){
  if (node.data === 'two') {
      console.log(node);
  }
}, tree.traverseBF);
b.查找
  // tree is an example of a root node
tree.contains(function(node){
    if (node.data === 'two') {
        console.log(node);
    }
}, tree.traverseBF);
c.添加
Tree.prototype.add = function(data, toData, traversal) {
  var child = new Node(data),
        parent = null,
        callback = function(node) {
          if (node.data === toData) {
            parent = node;
          }
        };

  this.contains(callback, traversal);//不要忘記回調查找

  if (parent) {
    parent.children.push(child);
    child.parent = parent;
  } else {
    throw new Error('Cannot add node to a non-existent parent.');
  }
};

eg:

var tree = new Tree('CEO');
tree.add('VP of Happiness', 'CEO', tree.traverseBF);

/*
our tree
'CEO'
└── 'VP of Happiness'
*/
d.刪除
Tree.prototype.remove = function(data, fromData, traversal) {
        var tree = this,
            parent = null,
            childToRemove = null,
            index;

        var callback = function(node) {
            if (node.data === fromData) {
                parent = node;
            }
        };

        this.contains(callback, traversal);

        if (parent) {
            index = findIndex(parent.children, data);

            if (index === undefined) {
                throw new Error('Node to remove does not exist.');
            } else {
                childToRemove = parent.children.splice(index, 1);
            }
        } else {
            throw new Error('Parent does not exist.');
        }

        return childToRemove;
    };
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 定義 從圖中某一頂點出發訪遍圖中其余頂點,且使每一個頂點僅被訪問一次,這個訪問的過程叫做圖的遍歷(Traversi...
    JarryWell閱讀 23,328評論 0 9
  • 1.JQuery 基礎 改變web開發人員創造搞交互性界面的方式。設計者無需花費時間糾纏JS復雜的高級特性。 1....
    LaBaby_閱讀 1,200評論 0 1
  • 計算機基礎 三級存儲系統的結構 計算機的三級存儲系統是什么?答:計算機系統中存儲層次可分為三級:高速緩沖存儲器、主...
    臭墨魚閱讀 5,107評論 0 7
  • 一直以來,我都很少使用也避免使用到樹和圖,總覺得它們神秘而又復雜,但是樹在一些運算和查找中也不可避免的要使用到,那...
    24K男閱讀 6,780評論 5 14
  • 1.JQuery 基礎 改變web開發人員創造搞交互性界面的方式。設計者無需花費時間糾纏JS復雜的高級特性。 1....
    LaBaby_閱讀 1,367評論 0 2