美文网首页Algorithm
144. Binary Tree Preorder Traver

144. Binary Tree Preorder Traver

作者: 世界上的一道风 | 来源:发表于2019-07-19 21:30 被阅读0次

Given a binary tree, return the preorder traversal of its nodes' values.
把访问到的右子树的地址压入栈:之后再根据栈是否为空,遍历所有的右子树,同时继续对新的右子树做压栈:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> ans;
        stack<TreeNode*> st;
        while(root)
        {
            ans.push_back(root->val);
            if (root->right)
                st.push(root->right);
            root = root->left;
        }
        TreeNode *P=NULL;
        while(!st.empty())
        {
            P = st.top();
            st.pop();
            while(P){
                ans.push_back(P->val);
                if(P->right) st.push(P->right);
                P = P->left;
            }
        }
        return ans;
    }
};

相关文章

网友评论

    本文标题:144. Binary Tree Preorder Traver

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