Leetcode 94 Binary Tree Inorder Traversal

2018-01-12 14:59:31 浏览数 (1)

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

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

代码语言:javascript复制
   1
    
     2
    /
   3

return [1,3,2].

二叉树中序遍历。

先贴一个递归的做法,

代码语言:javascript复制
/**
 * 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;
    }
};

再贴一个迭代的做法

代码语言:javascript复制
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;
    }
};

0 人点赞