zoukankan      html  css  js  c++  java
  • LC 94. Binary Tree Inorder Traversal

    问题描述

    Given a binary tree, return the inorder traversal of its nodes' values. (左 - 根 - 右)

    Example:

    Input: [1,null,2,3]
       1
        
         2
        /
       3
    
    Output: [1,3,2]

    Follow up: 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         // init
    14         vector<int> res;
    15         stack<TreeNode* > st;
    16         TreeNode* p = root; // 初始化根节点
    17         
    18         while(p||!st.empty()){
    19             // 一旦遇到节点,先考虑左边的,直到尽头,如果没有之后的右node,就停止运行了
    20             while(p){
    21                 st.push(p);
    22                 p = p->left;
    23             }
    24             // 立刻提取p的信息,并且把p弹出来。如果进入while,那么这一步只会是左孩子,如果没进入while,那么会是父节点/右节点。
    25             p = st.top();
    26             st.pop();
    27             res.push_back(p->val);
    28              // 把p 变成p的右孩子
    29            p = p->right; 
    30         }
    31         return res;
    32     }
    33 };            
  • 相关阅读:
    打印日志宏定义
    数据库读写操作
    SQL语句组成
    MySQL数据库的使用
    ubuntu下解决MySQL 1045 error
    css样式优先级
    redis
    dubbo
    maven
    Mybatis笔记
  • 原文地址:https://www.cnblogs.com/kykai/p/11582784.html
Copyright © 2011-2022 走看看