zoukankan      html  css  js  c++  java
  • [leetcode]Binary Tree Preorder Traversal

    先序遍历的非递归版本也是和中序遍历相似,不停处理当前节点,push入栈,同时向左下走,走不成了(NULL)就换右子树。也请看图加深印象。

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

      

  • 相关阅读:
    Python Day14
    Python Day13
    Python Day12
    Python Day11
    Python Day10
    Python Day9
    Python Day8
    Python Day7
    Python Day6
    Python Day5
  • 原文地址:https://www.cnblogs.com/lautsie/p/3418670.html
Copyright © 2011-2022 走看看