美文网首页
二叉树专题

二叉树专题

作者: 风之羁绊 | 来源:发表于2019-07-25 16:10 被阅读0次

    二叉树3大遍历:先序,中序,后序
    非递归版本:https://www.jianshu.com/p/373a002c401b

    先序:
    class Solution {
    public:
        vector<int> ans;
        std::stack<TreeNode *> s;
        vector<int> preorderTraversal(TreeNode * root) {
            // write your code here
            auto cur=root;
            while(cur||s.size())
            {
                while(cur)
                {
                    ans.push_back(cur->val);
                    s.push(cur);
                    cur=cur->left;
                }
                cur=s.top();
                s.pop();
                cur=cur->right;
            }
            return ans;
        }
    };
    
    中序
    class Solution {
    public:
        /**
         * @param root: A Tree
         * @return: Inorder in ArrayList which contains node values.
         */
        vector<int> ans;
        stack<TreeNode *> s;
        vector<int> inorderTraversal(TreeNode * root) {
            // write your code here
            auto cur=root;
            while(cur||s.size())
            {
                while(cur)
                {
                    s.push(cur);
                    cur=cur->left;
                }
                cur=s.top();
                s.pop();
                ans.push_back(cur->val);
                cur=cur->right;
            }
            return ans;
        }
    };
    
    后序遍历
    class Solution {
    public:
        /**
         * @param root: A Tree
         * @return: Postorder in ArrayList which contains node values.
         */
        vector<int> ans;
        std::stack<TreeNode *> s;
        vector<int> postorderTraversal(TreeNode * root) {
            // write your code here
            auto cur=root;
            TreeNode * last=NULL;
            while(cur||s.size())
            {
                while(cur)
                {
                    s.push(cur);
                    cur=cur->left;
                }
                cur=s.top();
                if(cur->right==NULL||cur->right==last)
                {
                    ans.push_back(cur->val);
                    s.pop();
                    last=cur;
                    cur=NULL;
                }
                else
                    cur=cur->right;
            }
            return ans;
        }
    };
    
    1. 二叉树的最近公共祖先

    相关文章

      网友评论

          本文标题:二叉树专题

          本文链接:https://www.haomeiwen.com/subject/nzyqrctx.html