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,null,2,3],

       1
        
         2
        /
       3

    return [1,3,2].

    递归

    /**
     * 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> inorder;
        vector<int> inorderTraversal(TreeNode* root) {
            if (root == nullptr)
                return inorder;
            inorderTraversal(root->left);
            inorder.push_back(root->val);
            inorderTraversal(root->right);
            return inorder;
        }
    };
    // 0 ms

    迭代

    /**
     * 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> inorder;
        vector<int> inorderTraversal(TreeNode* root) {
            if (root == nullptr)
                return inorder;
            stack<TreeNode*> stk;
            while (root != nullptr || !stk.empty()) {
                if (root != nullptr) {
                    stk.push(root);
                    root = root->left;
                }
                else {
                    root = stk.top();
                    stk.pop();
                    inorder.push_back(root->val);
                    root = root->right;
                }
            }
            return inorder;
        }
    };
    // 3 ms
  • 相关阅读:
    vue-element-admin 权限的添加
    vue 图标通过组件的方式引用步骤
    linux系统环境下配置vue项目运行环境
    5.5 卷积神经网络(LeNet)
    5.4 池化层
    5.3 多输入通道和多输出通道
    5.2 填充和步幅
    html && CSS
    P2827 [NOIP2016 提高组] 蚯蚓
    5.1 二维卷积层
  • 原文地址:https://www.cnblogs.com/immjc/p/7500494.html
Copyright © 2011-2022 走看看