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%内容,订阅专栏后可继续查看/也可单篇购买
前端岗位面试真题宝典 文章被收录于专栏
本面试宝典均来自校招面试题目大数据进行的整理
