Leetcode 94 Binary Tree Inorder Traversal

来源:互联网 发布:mac装不了软件说版本低 编辑:程序博客网 时间:2024/06/05 08:32

Q:

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

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

   1    \     2    /   3

return [1,3,2].


A:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> result;
    
    void dfs(TreeNode *p)
    {
        if(p->left!=NULL){
            dfs(p->left);
        }
            
        result.push_back(p->val);
        if(p->right!=NULL) {
            dfs(p->right);
        }
            
        return;
    }
    
    vector<int> inorderTraversal(TreeNode* root) {
        TreeNode * head = root;
        
        result.clear();
        
        if(head!=NULL){
            dfs(head);
        }
            
        return result;       
    }
};

原创粉丝点击