Leetcode 94 Binary Tree Inorder Traversal

来源:互联网 发布:海尔阿里云电视刷系统 编辑:程序博客网 时间:2024/06/05 06:50

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

二叉树中序遍历。

先贴一个递归的做法,

/** * 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:    void dfs(TreeNode* root,vector<int>& res)    {        if(root->left) dfs(root->left,res);        res.push_back(root->val);        if(root->right)dfs(root->right,res);    }    vector<int> inorderTraversal(TreeNode* root) {        vector<int> res;        if(root) dfs(root,res);        return res;    }};
再贴一个迭代的做法

class Solution {public:    vector<int> inorderTraversal(TreeNode* root) {        vector<int> res;        TreeNode *p=root;        vector<TreeNode*> s;        if(!root) return res;        while(p)        {            s.push_back(p);            p=p->left;        }        while(!s.empty())        {            p=s[s.size()-1];            res.push_back(p->val);            s.pop_back();            if(p->right)            {                p=p->right;                while(p)                {                    s.push_back(p);                    p=p->left;                }            }        }        return res;    }};



1 0