博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[leetCode] Binary Tree Inorder Traversal
阅读量:4184 次
发布时间:2019-05-26

本文共 1203 字,大约阅读时间需要 4 分钟。

题目:
Given a binary tree, return the inorder traversal of its nodes' values.For example:Given binary tree {
1,#,2,3}, 1 \ 2 / 3return [1,3,2].Note: Recursive solution is trivial, could you do it iteratively?
思路:

不断访问其左子树,然后输出其根,然后访问其接着的右子树,重复过程

实现代码如下:

#include 
#include
#include
#include
using namespace std;struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution {public: vector
inorderTraversal(TreeNode *root) { vector
v; if (root == NULL){ return v; } // 根节点入栈 stack
stack; TreeNode* node = root; // 遍历 while(node != NULL || !stack.empty()){ //遍历左子树 if(node != NULL){ stack.push(node); node = node->left; } else{ //左子树为空,访问右子树 node = stack.top(); stack.pop(); v.push_back(node->val); node = node->right; } } return v; }};//按先序序列创建二叉树int CreateBTree(TreeNode* &T){ char data; //按先序次序输入二叉树中结点的值(一个字符),‘#’表示空树 cin>>data; if(data == '#'){ T = NULL; } else{ T = (TreeNode*)malloc(sizeof(TreeNode)); //生成根结点 T->val = data-'0'; //构造左子树 CreateBTree(T->left); //构造右子树 CreateBTree(T->right); } return 0;}

转载地址:http://kxuoi.baihongyu.com/

你可能感兴趣的文章
Mysql中下划线问题
查看>>
Xcode 11 报错,提示libstdc++.6 缺失,解决方案
查看>>
vue项目打包后无法运行报错空白页面
查看>>
1136 . 欧拉函数
查看>>
面试题:强制类型转换
查看>>
Decorator模式
查看>>
Template模式
查看>>
Observer模式
查看>>
高性能服务器设计
查看>>
图文介绍openLDAP在windows上的安装配置
查看>>
Pentaho BI开源报表系统
查看>>
Pentaho 开发: 在eclipse中构建Pentaho BI Server工程
查看>>
android中SharedPreferences的简单例子
查看>>
android中使用TextView来显示某个网址的内容,使用<ScrollView>来生成下拉列表框
查看>>
andorid里关于wifi的分析
查看>>
Hibernate和IBatis对比
查看>>
Spring MVC 教程,快速入门,深入分析
查看>>
Ubuntu Navicat for MySQL安装以及破解方案
查看>>
在C++中如何实现模板函数的外部调用
查看>>
HTML5学习之——HTML 5 应用程序缓存
查看>>