leetcode Question 11: Binary Tree Inorder Traversal

Binary Tree Inorder Traversal

Given a binary tree, return the inorder traversal of its nodes' values.
For example: Given binary tree {1,#,2,3},
   1
    \
     2
    /
   3
return [1,3,2].

Analysis:

Classic tree operation, recursion is a straightforward idea to solve this problem.
Recursively do:
(1) Visit left child
(2) Output current node
(3) Visit right child
if current node is empty, return.

Code(C++):

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void inOrder(TreeNode *root, vector<int> &res){
        if (root!=NULL){
            inOrder(root->left,res);
            res.push_back(root->val);
            inOrder(root->right,res);
        }
    }
    vector<int> inorderTraversal(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<int> res;    
        inOrder(root,res);
        return res;
    }
};

Code(python):

# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @param root, a tree node
    # @return a list of integers
    res = []
    def iot(self, root):
        if root == None:
            return
        else:
            self.iot(root.left)
            self.res.append(root.val)
            self.iot(root.right)
            
    def inorderTraversal(self, root):
        self.res = []   #reset the result list
        self.iot(root)
        return self.res
        

No comments:

Post a Comment