Binary Tree Inorder Traversal(C++二叉樹的中序遍歷)

解題思路:

(1)遞歸求解

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: A Tree
     * @return: Inorder in ArrayList which contains node values.
     */
    vector<int> v;
    vector<int> inorderTraversal(TreeNode * root) {
        // write your code here
        inorder(root);
        return v;
    }
    
    void inorder(TreeNode *root) {
        if (root) {
            inorder(root->left);
            v.push_back(root->val);
            inorder(root->right);
        }
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章