LeetCode

Binary Tree Inorder Traversal

2013.12.31 18:26

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].

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

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

   1
  / 
 2   3
    /
   4
    
     5

The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".

Solution:

  Here is the definition for in-order traversal of a binary tree, click here.

  Time comlexity is O(n), space complexity is O(1), where n is the number of nodes in the tree.

Accepted code:

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<int> inorderTraversal(TreeNode *root) {
13         // IMPORTANT: Please reset any member data you declared, as
14         // the same Solution instance will be reused for each test case.
15         res.clear();
16         if(root == nullptr){
17             return res;
18         }
19         
20         inorder(root);
21         
22         return res;
23     }
24 private:
25     vector<int> res;
26     void inorder(TreeNode *root) {
27         if(root == nullptr){
28             return;
29         }else{
30             if(root->left != nullptr){
31                 inorder(root->left);
32             }
33             res.push_back(root->val);
34             if(root->right != nullptr){
35                 inorder(root->right);
36             }
37         }
38     }
39 };
原文地址:https://www.cnblogs.com/zhuli19901106/p/3499904.html