leetcode94.144.145二叉树遍历---前中后(递归,非递归)---C++/Java 实现

本文详细介绍了二叉树的前序、中序和后序遍历算法,包括递归和非递归两种实现方式,并提供了C++和Java代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

二叉树:

前序:    1-2-4-8-5-9-3-6-10-7   根左右

中序:    8-4-2-5-9-1-6-10-3-7   左根右

后序列: 8-4-9-5-2-10-6-7-3-1   左右根

 

递归实现

#include <iostream>
#include <stack>
#include <list>
#include <vector>

using namespace std;
struct TreeNode {
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

TreeNode *inorder(TreeNode* root,vector<int>& res)
{
	if(root!=NULL)
	{
		res.push_back(root->val);
		inorder(root->left,res);
		inorder(root->right,res);
	}
	else
		return NULL;
	return root;
}
int main()
{
	TreeNode *root=&TreeNode(1);
	root->left=&TreeNode(2);
	root->right=&TreeNode(3);
	root->left->left=&TreeNode(4);
	root->left->right=&TreeNode(5);
	root->right->left=&TreeNode(6);
	root->right->right=&TreeNode(7);
	root->left->left->left=&TreeNode(8);
	root->left->right->right=&TreeNode(9);
	root->right->left->right=&TreeNode(10);
	vector<int> myvec;
	TreeNode *outp=inorder(root,myvec);
	cout<<myvec[0];
	for(int i=1;i<myvec.size();i++)
		cout<<" "<<myvec[i];
	cout<<endl;

	return 0;
}

更改18.19.20三行的顺序,即可得到前中后序

 

非递归实现

前序

主要思路:

利用堆栈模拟路线,数组存储前序结果。步骤如下:

 

while(指针不为空||堆栈不为空)

  1. 判断当前指针是否为空
  2. 如果不为空,将数据放入堆栈s,同时将值放入数组,将指针指向左儿子
  3. 如果为空,指针指向栈顶元素的右儿子,同时出栈
#include <iostream>
#include <stack>
#include <list>
#include <vector>

using namespace std;
struct TreeNode {
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

vector<int> preorderTraversal(TreeNode* root) {
	vector<int> myvec;
	stack<TreeNode*> s;
	TreeNode* tmp=root;

	while (tmp||!s.empty())
	{
		if (tmp){
			s.push(tmp);
			myvec.push_back(tmp->val);
			tmp=tmp->left;
		} else{
			tmp=s.top()->right;
			s.pop();
		}
	}
	return myvec;
}
int main()
{
	TreeNode *root=&TreeNode(1);
	root->left=&TreeNode(2);
	root->right=&TreeNode(3);
	root->left->left=&TreeNode(4);
	root->left->right=&TreeNode(5);
	root->right->left=&TreeNode(6);
	root->right->right=&TreeNode(7);
	root->left->left->left=&TreeNode(8);
	root->left->right->right=&TreeNode(9);
	root->right->left->right=&TreeNode(10);
	vector<int> myvec;
	myvec=preorderTraversal(root);
	cout<<myvec[0];
	for(int i=1;i<myvec.size();i++)
		cout<<" "<<myvec[i];
	cout<<endl;

	return 0;
}

中序:

while条件:输入节点不为空,堆栈不为空

如果有左儿子,就一直循环往堆栈放左儿子

如果没有左儿子了,并且堆栈不为空,指针指向栈顶的元素,出栈,然后元素放入数组,

最后把指针指向栈顶元素的右儿子(左先已经出栈,跟紧接着,现在出栈右边)

vector<int> inorderTraversal(TreeNode* root) {
	vector<int> myvec;
	stack<TreeNode*> s;
	TreeNode* tmp=root;

	while (tmp||!s.empty())
	{
		while (tmp){
			s.push(tmp);
			tmp=tmp->left;
		}
		if (!s.empty()){
			tmp=s.top();
			s.pop();
			myvec.push_back(tmp->val);
			tmp=tmp->right;
		}
	}
	return myvec;
}

后序遍历

二叉树的后序遍历(leetcode 145)

vector<int> postorderTraversal(TreeNode* root) {
	stack<TreeNode*> s;
	vector<int> retVec;
	TreeNode* current = root;
	TreeNode* pre = nullptr;
	while(!s.empty()||current){
		while(current) {
			s.push(current);
			current = current->left;
		}
		auto top = s.top();
		if(top->right==nullptr||top->right==pre) {
			pre = top;
			retVec.push_back(top->val);
			current = nullptr;
			s.pop();
		}
		else {
			current = top->right;
		}
	}
	return retVec;
}

 Java实现:

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class BinaryTree {

    int val;
    BinaryTree left;
    BinaryTree right;

    BinaryTree(int val) {
        this.val = val;
    }

    BinaryTree(int val, BinaryTree left, BinaryTree right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }

    private static void outPreOrder(BinaryTree node) {
        if (node != null) {
            System.out.println(node.val);
            outPreOrder(node.left);
            outPreOrder(node.right);
        }
    }
    
    private static void outMiddleOrder(BinaryTree node) {
        if (node != null) {
            outMiddleOrder(node.left);
            System.out.println(node.val);
            outMiddleOrder(node.right);
        }
    }

    private static void outBackOrder(BinaryTree node) {
        if (node != null) {
            outBackOrder(node.left);
            outBackOrder(node.right);
            System.out.println(node.val);
        }
    }

    public static void main(String[] args) {
        BinaryTree root = new BinaryTree(1, new BinaryTree(2), new BinaryTree(3));
        root.left.left = new BinaryTree(4);
        root.left.left.left = new BinaryTree(8);
        root.left.right = new BinaryTree(5);
        root.left.right.right = new BinaryTree(9);
        root.right.left = new BinaryTree(6);
        root.right.right = new BinaryTree(7);
        root.right.left.right = new BinaryTree(10);
//        BinaryTree root = null;
        System.out.println("前序递归遍历");
        outPreOrder(root);
        System.out.println("前序非递归遍历");
        System.out.println(outPreOrderNotRec(root));
        System.out.println("中序递归遍历");
        outMiddleOrder(root);
        System.out.println("中序非递归遍历");
        System.out.println(outMiddleOrderNotRec(root));
        System.out.println("后序递归遍历");
        outBackOrder(root);
        System.out.println("后序非递归遍历");
        System.out.println(outBackOrderNotRec(root));
    }

    private static List<Integer> outBackOrderNotRec(BinaryTree node) {
        Stack<BinaryTree> stack = new Stack<>();
        List<Integer> vals = new ArrayList<>();
        BinaryTree pre = null;
        while (node != null || !stack.empty()) {
            while (node != null) {
                stack.add(node);
                node = node.left;
            }
            BinaryTree top = stack.peek();
            if (top.right == null || top.right == pre) {
                vals.add(top.val);
                pre = stack.pop();
            } else {
                node = top.right;
            }
        }

        return vals;
    }

    private static List<Integer> outMiddleOrderNotRec(BinaryTree node) {
        List<Integer> vals = new ArrayList<>();
        Stack<BinaryTree> stack = new Stack<>();
        while (node != null || !stack.empty()) {
            while (node != null) {
                stack.add(node);
                node = node.left;
            }
            if (!stack.empty()) {
                vals.add(stack.peek().val);
                node = stack.pop().right;
            }
        }
        return vals;
    }

    private static List<Integer> outPreOrderNotRec(BinaryTree node) {
        List<Integer> vals = new ArrayList<>();
        Stack<BinaryTree> stack = new Stack<>();
        while (node != null || !stack.empty()) {
            if (node != null) {
                stack.add(node);
                vals.add(node.val);
                node = node.left;
            } else {
                node = stack.pop().right;
            }
        }
        return vals;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值