94. Binary Tree Inorder Traversal
in LeetCodeAlgorithms with 0 comment

94. Binary Tree Inorder Traversal

in LeetCodeAlgorithms with 0 comment
  1. Binary Tree Inorder Traversal

Given a binary tree, return the inorder traversal of its nodes' values.

For example:
Given binary tree [1,null,2,3],

   1
    \
     2
    /
   3

return [1,3,2].

//https://leetcode.com/problems/binary-tree-inorder-traversal/description/
//两个思路:1、递归。2、非递归,借用栈

#include<iostream>
#include<vector>
#include<stack>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}

};

class Solution {
public:
    void inorder(TreeNode* root, vector<int> &answer) {
        if (root == NULL) {
            return;
        }
        inorder(root->left, answer);
        answer.push_back(root->val);
        inorder(root->right, answer);
    }
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> answer;
        inorder(root, answer);
        return answer;
    }
};
/*
中序遍历非递归:
1、借助栈,将整个树的左边界依次入栈(root=root->left)
2、若root为空,则弹出栈顶node并打印,另root=node.right,然后重复1
3、直到栈为空或root为空,结束
*/
class Solution1 {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> answer;
        stack<TreeNode>temp;
        while (!temp.empty() || root) {
            if (root) {
                temp.push(*root);
                root = root->left;
            }
            else {
                answer.push_back(temp.top().val);
                root = temp.top().right;
                temp.pop();
            }
        }
        return answer;
    }
};
int main() {
    TreeNode *a = new TreeNode(1);
    TreeNode *b = new TreeNode(2);
    TreeNode *c = new TreeNode(3);
    a->right = b;
    b->left = c;
    Solution1 test;
    vector<int> answer = test.inorderTraversal(a);
    for (int i = 0; i < answer.size(); i++) {
        cout << answer[i]<<" ";
    }
    return 0;
}
Responses

From now on, bravely dream and run toward that dream.
陕ICP备17001447号