美文网首页
Binary Tree Traversal 小结

Binary Tree Traversal 小结

作者: stepsma | 来源:发表于2020-04-01 01:10 被阅读0次

    本文总结了tree的三种traversal方式, 三种都用到stack。而且只有在inorder的时候while condition有所不同

    1. Inorder Traversal
      https://leetcode.com/problems/binary-tree-inorder-traversal/

    while(cur || !st.empty()), 同时while loop之前不 push stack

    class Solution {
    public:
        vector<int> inorderTraversal(TreeNode* root) {
            vector<int> ret;
            if(!root){
                return ret;
            }
            
            stack<TreeNode*> st;
            TreeNode *cur = root;
            
            while(cur || !st.empty()){
                if(cur){
                    st.push(cur);
                    cur = cur->left;
                }
                else{
                    TreeNode *node = st.top(); st.pop();
                    ret.push_back(node->val);
                    cur = node->right;
                }
            }
            
            return ret;
        }
    };
    
    1. Preorder Traversal
      https://leetcode.com/problems/binary-tree-preorder-traversal/

    while(!st.empty()), , 同时while loop之前 push stack

    class Solution {
    public:
        vector<int> preorderTraversal(TreeNode* root) {
            if(!root){
                return vector<int>();
            }
            
            vector<int> ret;
            stack<TreeNode*> st;
            st.push(root);
            
            while(!st.empty()){
                TreeNode *node = st.top(); st.pop();
                ret.push_back(node->val);
                if(node->right){
                    st.push(node->right);
                }
                
                if(node->left){
                    st.push(node->left);
                }
            }
            
            return ret;
        }
    };
    
    1. Postorder Traversal:
      https://leetcode.com/problems/binary-tree-postorder-traversal/

    Postorder 与 Preorder模板差不多,只是最后要reverse

    class Solution {
    public:
        vector<int> postorderTraversal(TreeNode* root) {
            vector<int> ret;
            if(!root){
                return ret;
            }
            
            stack<TreeNode*> st;
            st.push(root);
            
            while(!st.empty()){
                TreeNode* node = st.top(); st.pop();
                ret.push_back(node->val);
                if(node->left){
                    st.push(node->left);
                }
                
                if(node->right){
                    st.push(node->right);
                }
            }
            
            reverse(ret.begin(), ret.end());
            return ret;
        }
    };
    

    相关文章

      网友评论

          本文标题:Binary Tree Traversal 小结

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