1. ?LeetCode刷題實戰(zhàn)144:二叉樹的前序遍歷

        共 1339字,需瀏覽 3分鐘

         ·

        2021-01-04 20:27

        算法的重要性,我就不多說了吧,想去大廠,就必須要經(jīng)過基礎知識和業(yè)務邏輯面試+算法面試。所以,為了提高大家的算法能力,這個公眾號后續(xù)每天帶大家做一道算法題,題目就從LeetCode上面選 !

        今天和大家聊的問題叫做?二叉樹的前序遍歷,我們先來看題面:
        https://leetcode-cn.com/problems/binary-tree-preorder-traversal/

        Given the root of a binary tree, return the preorder traversal of its nodes' values.

        題意


        給你二叉樹的根節(jié)點 root ,返回它節(jié)點值的 前序 遍歷。

        樣例


        解題

        遞歸法:

        定義一個存放樹中數(shù)據(jù)的向量 data,從根節(jié)點開始,如果節(jié)點不為空,那么

        將當前節(jié)點的數(shù)值加入到 data 中
        遞歸得到其左子樹的數(shù)據(jù)向量 temp,將 temp 合并到 data 中去
        遞歸得到其右子樹的數(shù)據(jù)向量 temp,將 temp 合并到 data 中去

        /**
        ?* 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?{
        public:
        ????vector<int> preorderTraversal(TreeNode* root) {
        ????????
        ????????vector<int> data = {};
        ????????vector<int> temp = {};

        ????????if?(root != NULL)
        ????????{
        ????????????data.push_back(root->val);
        ????????????temp = preorderTraversal(root->left);
        ????????????data.insert(data.end(),temp.begin(),temp.end());
        ????????????temp = preorderTraversal(root->right);
        ????????????data.insert(data.end(),temp.begin(),temp.end());
        ????????}
        ????????
        ????????return?data;
        ????}
        };


        好了,今天的文章就到這里,如果覺得有所收獲,請順手點個在看或者轉(zhuǎn)發(fā)吧,你們的支持是我最大的動力。

        上期推文:

        LeetCode1-140題匯總,希望對你有點幫助!
        LeetCode刷題實戰(zhàn)141:環(huán)形鏈表
        LeetCode刷題實戰(zhàn)142:環(huán)形鏈表 II
        LeetCode刷題實戰(zhàn)143:重排鏈表


        瀏覽 33
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
        評論
        圖片
        表情
        推薦
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
          
          

            1. 国内精品久久久久影院男同志 | 办公室被吃奶好爽动态图 | 国产日韩欧美一区二区东京热 | 亚洲 自拍 另类小说综合图区 | 午夜成人免费毛片 |