二叉树的中序遍历

来源:互联网 发布:visor是什么软件 编辑:程序博客网 时间:2024/06/03 18:41

问题描述:

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

样例

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

   1    \     2    /   3

返回 [1,3,2].

解题思路:

运用递归,先访问二叉树的左子树输出数据,然后输出根节点的数据,最后访问右子树输出数据。

代码描述:

/**
 * 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> l;
        if(root==NULL) return l;
        func(root,l);
        return l;
    }
    void func(TreeNode *root,vector<int> &l){
        if(root==NULL) return;
        func(root->left,l);
        l.push_back(root->val);
        func(root->right,l);
    }
};

解题感想:

解决方法同前序遍历。

0 0
原创粉丝点击