leetcode 94 binary tree traversal sequence (non-recursive)

Binary tree? Preorder

Title:
Given a binary tree, it returns preorder

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

Topic analysis

Preorder:

  • Left subtree
  • Root
  • Right subtree

Recursive three lines to solve the
non-recursive? Stack Save Node Information

Problem-solving ideas

variable effect
stack<TreeNode*> s Save Node Information
TreeNode* temp Indicates that the current access node

Process:
When s non-empty
remove the top element as a current node temp
top element from the stack
if the current node's right child node nonempty ==> stack
(Stack advanced after it first right subtree of node stack)

If the current node's left child node of the tree is not empty
==>
1. Current temp node re-stack (such complete traverse the left subtree when you can re-iterate back to the root node)
2. The current node in the left subtree of the stack
3. the current nodeLeft and right subtrees as null(Again, traversing the time is equivalent to no left and right sub-tree root node output information)

code show as below

class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        if (!root) return {};
        stack<TreeNode*> s{{root}};
        vector<int> ans;
        while(!s.empty())
        {
            TreeNode* temp;
            temp = s.top();
            s.pop();
            if (temp->right) s.push(temp->right);    //右子树节点入栈
            if (temp->left) 
            {
                s.push(temp);
                s.push(temp->left);
                temp->left = NULL;
                temp->right = NULL;
            }
            else ans.push_back(temp->val);   //左子树节点为空则输出本节点信息
        }
        return ans;
    }
};
发布了34 篇原创文章 · 获赞 0 · 访问量 584

Guess you like

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