二叉树的中序遍历

来源:互联网 发布:java 命名管道 编辑:程序博客网 时间:2024/06/05 16:20

问题描述:

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

样例:

给出二叉树 {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;
 *     }
 * }
 */
    vector<int> tree;
class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: Inorder in vector which contains node values.
     */
public:
    void InorderTraversal(TreeNode *root) {
        if (root== NULL)return;
        InorderTraversal(root->left);
        tree.push_back(root->val);
        InorderTraversal(root->right);
    }
    vector<int> inorderTraversal(TreeNode *root) {
        // write your code here
        if (root== NULL) return tree;
        InorderTraversal(root);
        return tree;
    }
};

感想:

跟前序遍历基本思路是一样的。


0 0
原创粉丝点击