1. 程式人生 > >演算法練習筆記(八)—— 樹的BFS遍歷

演算法練習筆記(八)—— 樹的BFS遍歷

BFS遍歷,廣度優先搜尋,在用法上來說和這周所學的貪心演算法有著很大程度上的相似

與深度優先演算法不同的是,演算法會在遍歷完一棵樹中每一層的每個結點之後,才會轉到下一層繼續,在這一基礎上,二維陣列和佇列將會對演算法起到很大的幫助

題目地址:https://leetcode.com/problems/binary-tree-level-order-traversal/#/description

題目:Binary Tree Level Order Traversal

描述:

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:
Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]

BFS解答:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    
    vector<vector<int>> result;
    
public:
    void BFS(TreeNode * root, int dep){
        if(!root)return;
        if(result.size() == dep)
            result.push_back(vector<int>());
        result[dep].push_back(root -> val);
        BFS(root -> left, dep + 1);
        BFS(root -> right, dep + 1);
    }
    vector<vector<int>> levelOrder(TreeNode* root) {
        BFS(root, 0);
        return result;
    }
};