[従来のアルゴリズム]二叉木のDFS,BFS遍歴C++実装


1. DFS - use recursion
    void dfs (TreeNode* root) {

        if(root){

            cout << root->val << ' ';

            dfs(root->left);

            dfs(root->right);           

        }
    }

2. BFS – use iteration(queue)
   
     void bfs(TreeNode* root) {

        if(root){

            queue q;

            q.push(root);

           

            while(!q.empty()){

                for(int i = 0, n = q.size(); i < n; i++){

                    TreeNode* node = q.front();

                    cout << node->val << ' ';

                    q.pop();

                    if(node->left) q.push(node->left);

                    if(node->right) q.push(node->right);  

                }

                cout << endl;

            }

        }

    }

ツリーのデータ構造はleetcodeの書き方を参照します
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */