NC45实现二叉树先序,中序和后序遍历(递归)
NC45实现二叉树先序,中序和后序遍历(递归)
- 1、题目描述:
-3、 设计思想:
-5、代码:
c++版本:
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类 the root of binary tree
* @return int整型vector<vector<>>
*/
vector<int> pre;//存储先序遍历结果
vector<int> in;//存储中序遍历结果
vector<int> post;//存储后序遍历结果
/*先序遍历*/
void preOrderRecur(TreeNode *root) {
if (root == nullptr) return;
pre.push_back(root->val);//根
preOrderRecur(root->left);//左
preOrderRecur(root->right);//右
}
/*中序遍历*/
void inOrderRecur(TreeNode *root) {
if (root == nullptr) return;
inOrderRecur(root->left);//左
in.push_back(root->val);//根
inOrderRecur(root->right);//右
}
/*后序遍历*/
void posOrderRecur(TreeNode *root) {
if (root == nullptr) return;
posOrderRecur(root->left);//左
posOrderRecur(root->right);//右
post.push_back(root->val);//根
}
vector<vector<int> > threeOrders(TreeNode* root) {
// write code here
vector<vector<int>>res;//用于返回最终的结果
if(root == nullptr) return res;
preOrderRecur(root);//先序遍历
inOrderRecur(root);//中序遍历
posOrderRecur(root);//后序遍历
res.push_back(pre);//将先序遍历放进res
res.push_back(in);//将中序遍历放进res
res.push_back(post);//将后序遍历放进res
return res;
}
};
Java版本:
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类 the root of binary tree
* @return int整型二维数组
*/
ArrayList<Integer> pr
剩余60%内容,订阅专栏后可继续查看/也可单篇购买
C++岗位面试真题宝典 文章被收录于专栏
整篇专刊共分为6章,涵盖C++基础、C++操作系统、C++计算机网络、C++数据库、C++设计模式与算法面试真题。 购买须知 1、专刊报名后,在个人主页-学习-已购-专刊即可快速进入学习。2、专刊为虚拟商品,交付形式为图文,一经购买,即可解锁内容,所以概不退款。 3、专刊版权归本牛客所有,任何机构、媒体、网站或个人未经本网协议授权不得转载、链接、转贴或以其他方式复制发布/发表,违者将依法追究责任。
