二叉树中序遍历-lintcode
来源:互联网 发布:淘宝上的车秒贷靠谱吗 编辑:程序博客网 时间:2024/04/28 03:13
这个就是递归和非递归两种方法,非递归难一点,但是不用调用栈。
递归:
注意vector相接的方法,用insert(,,)。
C++代码:
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */class Solution { /** * @param root: The root of binary tree. * @return: Inorder in vector which contains node values. */public: vector<int> inorderTraversal(TreeNode *root) { vector<int> result; if(root==NULL) return result; vector<int> temp = inorderTraversal(root->left); result.insert(result.end(),temp.begin(),temp.end()); result.push_back(root->val); temp = inorderTraversal(root->right); result.insert(result.end(),temp.begin(),temp.end()); return result; }};
非递归:
使用一个TreeNode*的stack,每次都循环向stack中添加temp指向的左子树节点,然后用temp指针接受stack的pop(),使用这个指针后将它指向它的右子树,再次回到push()的循环中。
C++代码:
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */class Solution { /** * @param root: The root of binary tree. * @return: Inorder in vector which contains node values. */public: vector<int> inorderTraversal(TreeNode *root) { vector<int> result ; stack<TreeNode *> sta; TreeNode * temp = root; if (root == NULL) return result; while(!sta.empty() || temp!=NULL){ while(temp!=NULL){ sta.push(temp); temp = temp->left; } if(!sta.empty()){ temp = sta.top(); result.push_back(temp->val); sta.pop(); temp = temp->right; } } return result; }};
0 0
- Lintcode 二叉树中序遍历
- 二叉树中序遍历-lintcode
- Lintcode 二叉树前序遍历
- 二叉树层次遍历-LintCode
- lintcode.68 二叉树后序遍历
- LintCode-二叉树的层次遍历 II
- LintCode 二叉树的层次遍历
- LintCode 二叉树的层次遍历 II
- lintcode-二叉树的层次遍历-69
- LintCode -- 二叉树的前序遍历
- LintCode -- 二叉树的中序遍历
- LintCode -- 二叉树的后序遍历
- Lintcode 二叉树的后序遍历
- lintcode 二叉树的中序遍历
- lintcode 二叉树的前序遍历
- LintCode:二叉树的后序遍历
- Lintcode 二叉树后序遍历 非递归形式
- LintCode:二叉树的层次遍历
- Html 标签的嵌套规则
- HDU2973(威尔逊定理)
- Java IO模型
- haproxy 规则匹配到了就停止,不会继续匹配下一个
- Java设计模式之四——代理模式
- 二叉树中序遍历-lintcode
- JS获取表格单元格坐标及给指定单元格赋值
- 计算机网络整理(谢希仁版)
- 关于javascript词法分析的自己的理解。
- ui--UITabBarController
- tomcat7关键配置和线程
- 网易MySQL数据库工程师微专业学习笔记(一)
- kmp算法&&学习感想
- [嵌入式]Cortex-A8处理器编程(中)