二叉树的中序遍历

来源:互联网 发布:海关进出口数据查询 编辑:程序博客网 时间:2024/06/14 17: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.
     */
      void inorder(vector<int>&v,TreeNode *root){
          if(root==NULL) return ;
          inorder(v,root->left);
          v.push_back(root->val);
           inorder(v,root->right);
     }
public:
    vector<int> inorderTraversal(TreeNode *root) {
       vector<int> v;
       inorder(v,root);
       return v;
      // write your code here
    }
};

感悟:

注意中序遍历函数中的引用

0 0
原创粉丝点击