二叉树中序遍历

来源:互联网 发布:淘宝网点击结算没反应 编辑:程序博客网 时间:2024/06/03 12:24

给出一棵二叉树,返回其中序遍历

样例

给出二叉树 {1,#,2,3},

   1    \     2    /   3

返回 [1,3,2].

1.采用递归的方法 13ms

/** * Definition of TreeNode: * class TreeNode { * public: *     int val; *     TreeNode *left, *right; *     TreeNode(int val) { *         this->val = val; *         this->left = this->right = NULL; *     } * } */class Solution {    /**     * @param root: The root of binary tree.     * @return: Inorder in vector which contains node values.     */public:    vector <int> result;    vector<int> inorderTraversal(TreeNode *root) {        // write your code here        if(root){            inorderTraversal(root->left);            result.push_back(root->val);            inorderTraversal(root->right);        }        return result;    }};


0 0
原创粉丝点击