二叉树的中序遍历

来源:互联网 发布:网络招聘的优劣势 编辑:程序博客网 时间:2024/05/21 09:49

1.问题描述

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

样例

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

   1    \     2    /   3

返回 [1,3,2].


2.解题思路

运用递归的方式,按先左子树然后根节点最后右子树的思想将节点一个个保存到vector中。

3.代码实现

/**
 * 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> inorderTraversal(TreeNode *root) {
        // write your code here
        vector<int>r;
        inorder(r,root);
        return r;
    }
    void inorder(vector<int>& r,TreeNode*root)
    {
         if(root==NULL)
        return;
        inorder(r,root->left);
         r.push_back(root->val);
            inorder(r,root->right);
    }
};

4.感想

和前序遍历一样,vector 只能定义一次。

0 0
原创粉丝点击