二叉樹之前序遍歷(迭代法)

題源:https://leetcode-cn.com/problems/binary-tree-preorder-traversal/solution/

一、初始代碼:

class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        stack<TreeNode*> s;
        vector<int> res;
        TreeNode *r;
        if(root==NULL) return res; 
        s.push(root);
        r=s.top();
        while(r||!s.empty()){
            while(r){
                res.push_back(r->val);
                r=r->left;
                if(r!=NULL) s.push(r);
            }
            r=s.top();
            s.pop();
            if(r->right!=NULL) s.push(r->right);
            r=r->right;
        }
        return res;
    }
};

1、在解決樹的層序遍歷,中序遍歷後再解決前序遍歷,自然簡單些,很快就寫完了。主要在處理if(root) return res.出了差錯。

二、參考代碼

class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        std::stack<TreeNode*> stack;
        vector<int> vec;
        TreeNode* cur = root;
        while(cur != NULL || !stack.empty()) {
            while(cur != NULL) {
                stack.push(cur);
                vec.push_back(cur->val);
                cur = cur->left;
            }
            cur = stack.top();
            stack.pop();
            cur = cur->right;
        }
        return vec;
    }
};

作者:wang-mu-mu-17
鏈接:https://leetcode-cn.com/problems/binary-tree-preorder-traversal/solution/shu-de-qian-xu-bian-li-fei-di-gui-fang-fa-zhan-by-/
來源:力扣(LeetCode)
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。

1、看了別人的代碼才發現存在的差距(不管什麼時候,在自己找到解決方法的同時,也要去參考別人的方法,見賢思齊焉,見不賢而內自省也)

2、無需使用if語句判斷右子樹是否爲空,直接如下:

cur=cur->right;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章