• Leetcode-144. 二叉树的前序遍历


    给定一个二叉树,返回它的 前序 遍历。

     示例:

    输入: [1,null,2,3]
    1
     
      2
     /
    3

    输出: [1,2,3]
    进阶: 递归算法很简单,你可以通过迭代算法完成吗?

    递归解法:

    /**
     * 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<int> fNum;
    public:
        vector<int> preorderTraversal(TreeNode* root) {
            init();
            fDfs(root);
            return fNum;
        }
        void fDfs(TreeNode* root)
        {
            if (root!= NULL)
            {
                fNum.push_back(root->val);
                fDfs(root->left);  //遍历左子树
                fDfs(root->right);  //遍历右子树
            }
        }
        void init()
        {
            fNum.clear();
        }
    };

    迭代算法:

    /**
     * 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<int> num;
        stack<TreeNode* > fNum; 
    public:
        vector<int> preorderTraversal(TreeNode* root) {
            init();
            bfs(root);
            return num;
        }
        void bfs(TreeNode* root)
        {
            while (root!= NULL|| ! fNum.empty())
            {
                while (root!= NULL)
                {
                    fNum.push(root);
                    num.push_back(root->val);
                    root = root->left;
                }
                root = fNum.top();
                fNum.pop();
                root = root->right;
            }
        }
        void init()
        {
            num.clear();
            if(! fNum.empty()) fNum.pop();
        }
    };
  • 相关阅读:
    TWinHttp之二
    日志池
    TWinHTTP
    TJSONTableObject跨平台解析JSON
    TSQLTableJSON解析JSON
    TDocVariantData解析JSON
    Vue.js常用指令汇总(v-if//v-show//v-else//v-for//v-bind//v-on等)
    VUE -- 十分钟入门 Less
    VUE -- ejs模板的书写
    Go VUE --- vuejs在服务器部署?
  • 原文地址:https://www.cnblogs.com/Amaris-diana/p/13229668.html
Copyright © 2020-2023  润新知