94-Binary Tree Inorder Traversal

来源:互联网 发布:wow淘宝刷坐骑会封号吗 编辑:程序博客网 时间:2024/06/06 00:33

题目:

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].

分析:
二叉树的中序遍历
思路1:
递归
思路2:
用Stack 实现

实现:
思路1:

class Solution {public:    vector<int> inorderTraversal(TreeNode* root) {        vector<int> res;        inorder(root,res);        return res;    }    void inorder(TreeNode* root,vector<int>& res)    {        if(!root)            return;        inorder(root->left,res);        if(root)            res.push_back(root->val);        inorder(root->right,res);    }};

思路2:

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