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

    解题思路:

    迭代版:

     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         stack<TreeNode *> cache;
    15         TreeNode *p = root;
    16         
    17         while (!cache.empty() || p != nullptr) {
    18             if (p != nullptr) {
    19                 cache.push(p);
    20                 p = p->left;
    21             } else {
    22                 p = cache.top();
    23                 cache.pop();
    24                 result.push_back(p->val);
    25                 p = p->right;
    26             }
    27         }
    28         
    29         return result;
    30     }
    31 };

     递归版:

     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         if (root != nullptr) {
    14             inorderTraversal(root->left);
    15             result.push_back(root->val);
    16             inorderTraversal(root->right);
    17         }
    18         
    19         return result;
    20     }
    21 private:
    22     vector<int> result;
    23 };
  • 相关阅读:
    设置为自动启动的WindowService没有开机启动
    Asp.Net部署问题
    MSDTC的折磨
    C# WinForm 边框阴影窗体
    升级DotNetNuke
    常用缩写
    DotNetNuke的升级路径
    日本語文法勉強
    PostSubmitter~在WEB应用程序以外的其他程序里提交Web请求的类
    vue中的锚链接跳转问题
  • 原文地址:https://www.cnblogs.com/skycore/p/4986158.html
Copyright © 2011-2022 走看看