zoukankan      html  css  js  c++  java
  • 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].

    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.

     

    Analyse: root->left, root, root->right.

    1. Recursion

        Runtime: 0ms.

     1 /**
     2  * Definition for a binary tree node.
     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         vector<int> result;
    14         if(!root) return result;
    15         
    16         inorder(root, result);
    17         return result;
    18     }
    19     void inorder(TreeNode* root, vector<int>& result){
    20         if(root->left) inorder(root->left, result);
    21         result.push_back(root->val);
    22         if(root->right) inorder(root->right, result);
    23     }
    24 };

    2. Iteration

        Runtime: 0ms.

     1 /**
     2  * Definition for a binary tree node.
     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         vector<int> result;
    14         if(!root) return result;
    15         stack<TreeNode* > stk;
    16         
    17         while(root || !stk.empty()){
    18             if(root){
    19                 stk.push(root);
    20                 root = root->left;
    21             }
    22             else{
    23                 root = stk.top();
    24                 result.push_back(root->val);
    25                 stk.pop();
    26                 root = root->right;
    27             }
    28         }
    29         return result;
    30     }
    31 };
  • 相关阅读:
    以此来励志吧!!!(选自:知乎)
    【P1303】苹果二叉树
    【P1813】8的倍数
    2016.9.4 の 測試
    后缀数组
    个中模板
    基数排序
    【NOIP2014D2T3】解方程
    【HAOI2006】【BZOJ1051】【p1233】最受欢迎的牛
    java安全性-引用-分层-解耦
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4679898.html
Copyright © 2011-2022 走看看