zoukankan      html  css  js  c++  java
  • 二叉树的三种遍历(非递归)

    先定义二叉树:

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */

    二叉树的先序遍历(以LeetCode 144.为例):

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

      

    二叉树的中序遍历(以LeetCode 94.为例):

    class Solution {
    public:
        vector<int> inorderTraversal(TreeNode* root) {
            vector<int>ans;
            stack<TreeNode*>s;
            while(1){
                while(root){
                    s.push(root);
                    root=root->left;
                }
                if(s.empty()) break;
                root=s.top();
                s.pop();
                ans.push_back(root->val);
                root=root->right;
            }
            return ans;
        }
    };
    

      

    二叉树的后序遍历(以LeetCode 145.为例):

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

      

  • 相关阅读:
    OCP-1Z0-052-V8.02-157题
    OCP-1Z0-052-V8.02-72题
    error C2061: 语法错误 : 标识符“_DebugHeapTag”
    OCP-1Z0-052-V8.02-23题
    OCP-1Z0-052-V8.02-77题
    vc2005 使用Boost库的编译步骤.
    OCP-1Z0-052-V8.02-79题
    OCP-1Z0-052-V8.02-82题
    OCP-1Z0-052-V8.02-81题
    OCP-1Z0-052-V8.02-80题
  • 原文地址:https://www.cnblogs.com/20143605--pcx/p/5178682.html
Copyright © 2011-2022 走看看