LeetCode#94. Binary Tree Inorder Traversal

题目:

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

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


return [1,3,2].

Note: Recursive solution is trivial, could you do it iteratively?

题意:

二叉树的中序遍历,即按照结点左子树,结点,结点右子树这样输出,采用递归方式实现,一种c++的代码实现如下:

#include<iostream>
#include<cstdio>
#include<cstdlib>
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
using namespace std;
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> v;
        inorder(v,root);
        return v;
    }
    void inorder(vector<int>& v, TreeNode* t) {
        if(t == NULL) {
            return;
        }
        inorder(v,t->left);
        v.push_back(t->val);
        inorder(v,t->right);
    }
};


猜你喜欢

转载自blog.csdn.net/zc2985716963/article/details/78734511