(103)94. In-order traversal of binary tree (leetcode)

题目链接:
https://leetcode-cn.com/problems/binary-tree-inorder-traversal/
难度:中等
94. 二叉树的中序遍历
给定一个二叉树,返回它的中序遍历。
示例:
	输入: [1,null,2,3]
	   1
	    \
	     2
	    /
	   3
	输出: [1,3,2]
	进阶: 递归算法很简单,你可以通过迭代算法完成吗?

A simple batch without considering advanced. . . . Just recurse directly

/**
 * 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> inorderTraversal(TreeNode* root) {
    
    
        vector<int> ans;
        if(root==nullptr){
    
    
            return ans;
        }
        dfs(root,ans);
        return ans;
    }
    void dfs(TreeNode* root,vector<int> &ans){
    
    
        if(root->left!=nullptr){
    
    
            dfs(root->left,ans);
        }
        ans.push_back(root->val);
        if(root->right!=nullptr){
    
    
            dfs(root->right,ans);
        }
    }
};

Then the code is as follows when using iteration, and an error occurred when the iteration of the middle order traversal was not very proficient in writing. . . One place does not understand
root=root->right; Before that, the current node and the left subtree have been enumerated, and then the right subtree of the current node is to be enumerated. If the right subtree (or right node) of the current node is Empty then take sta.top() back in the next loop

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

Guess you like

Origin blog.csdn.net/li_qw_er/article/details/108572734