leetcode 144 preorder traversal of a binary tree (non-recursive)

Binary tree? Preorder traversal!

Title:
Given a binary tree in preorder traversal to return it.

Examples:
Input: [. 1, null, 2,3]
. 1
\
2
/
. 3
Output: [1,2,3]

Topic analysis

Preorder traversal
  • Root
  • Left subtree
  • Right subtree

Recursive three lines to solve
not use recursion? Stack saved node information can be!

Problem-solving ideas

variable effect
stack < Treenode * > s Save Node Information
TreeNode * temp The current traversing node \

Process:
When s non-empty
remove the top element as the current node temp
If the current node right subtree of node non-empty ==> stack
if the current node left subtree of node non-empty ==> stack
after (the first stack out - sofirstPlus right node againPlus the left node)

code show as below:

class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        if (!root) return {};
        vector<int> ans;
        stack<TreeNode*> s{{root}};
        while (!s.empty())
        {
            TreeNode* temp;
            temp = s.top();
            s.pop();
            ans.push_back(temp->val);
            if (temp->right) s.push(temp->right);    //右节点入栈
            if (temp->left) s.push(temp->left);        //左结点入栈
        }
        return ans;
    }
};
Published 34 original articles · won praise 0 · Views 586

Guess you like

Origin blog.csdn.net/Luyoom/article/details/103940467