记录 二叉树之前序、中序、后序遍历

记录一下关于二叉树的三种遍历方式,开阔下思维

前序遍历

前序遍历规则是: —>—>,结合运用相关知识,思路应该为:先打印根节点,按照右,左节点顺序(因为后进先出)依次进栈

const stack = []
const result = []
stack.push(tree)

while(stack.length && tree) {
    
    
	// 弹出最后一个
	stack.pop()
	result.push(tree.value)
	// 按照 右、左依次进栈
	if(tree.right) stack.push(tree.right)
	if(tree.left) stack.push(tree.left)
	// 去栈最后一个作为要处理的数据
	tree = stack[stack.length - 1]
}

中序遍历

中序遍历规则:—>—>,应该先遍历所有左节点,当没有时,取对栈顶点值,然后再遍历所有右节点

const stack = []
const result = []

while(stack.length || tree) {
    
    
	if(tree) {
    
    
		stack.push(tree)
		// 遍历左节点
		tree = tree.left
	}else{
    
    
		// 取栈顶
		tree = stack.pop()
		result.push(tree.value)
		// 遍历右节点
		tree = tree.right
	}
}

后序遍历

后序遍历规则:—>—>,运用两个栈,一个用于按照根、右、左方式进栈,后序就可以依次取出,另外一个就用于临时保存,且按照左、右顺序进栈(出时就为右、左)

const stack1 = []
const stack2 = []
const result = []
stack1.push(tree)

while(stack1.length) {
    
    
	tree = stack1.pop()
	// 按照 根、右、左进栈
	stack2.push(tree)
	//临时栈
	if(tree.left) stack1.push(tree.left)
	if(tree.right) stack1.push(tree.right)
}
//出栈即为 左、右、根
while(stack2.length) {
    
    
   result.push(stack2.pop().value)
}

猜你喜欢

转载自blog.csdn.net/qq_45219069/article/details/122855144