二叉树专题

二叉树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. 二叉树的最近公共祖先
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容