二叉树前序遍历递归和非递归解法

二叉树的前序遍历(递归版本和迭代版本)

递归实现

1.王道408c语言(答题)逻辑版本:

void preorder(BiTree T){
	if (T != NULL){  //判断树是否为空
		visit(T);  //访问根结点
		preorder(T->lchild) //访问左子树
		preorder(T->rchild) //访问又子树
	}
}

2.python版本:

(注意:python递归实现时,不能直接调用最外层递归函数)

def preorderTraversal(root):
	res = [] //记录节点的值
	def preorder(root):
		if not root: //判断树是否为空
			return res
		res.append(root.val)
		preorder(root.left)
		preorder(root.right)
	preorder(root) //执行函数
	return res
		

迭代实现

(需要借助栈)

1.王道408c语言(答题)逻辑版本:

void preorder(BiTree T){
	InitStack(s); //初始化栈
	BiTree p = T; //初始化指针
	while(p ||!isEmpty(s)){   //当p为空是可能是把p指向了空节点
		if(T){
			visit(p);
			push(s,p);
			p = p->lchild;
		}
		else{
			pop(s,p);
			p = p-> rchild; //判断右子树
		}
	}
}

2.python版本:

(注意:1.栈存放的是节点,需要另外的list来存放val)

void preorder(BiTree T){
	stack = []  //初始化栈,栈中放的是node
	res []  //res中保存val
	if not root:   //判空
		return res
	while root or len(stack) > 0:
		if root:
			res.append(root.val)
			stack.append(root)  //节点
			root = root.left
		else:
			n = stack.pop(-1)  //用n来记录弹出的node
			if n:
				root = n.right
	return res

例题:

给定一个二叉树,返回它的 前序 遍历。
输入: [1,null,2,3]  
   1
    \
     2
    /
   3 

输出: [1,2,3]
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def preorderTraversal(self, root: TreeNode) -> List[int]:
    
        res = []
        def preorder(root):
            if not root:
                return res
            res.append(root.val)
            preorder(root.left)
            preorder(root.right)
            
        preorder(root)
        return res
        '''
        stack =[]
        res =[]
        if not root:
            return res
        while root or len(stack) > 0:
            if root:
                stack.append(root)
                res.append(root.val)
                root = root.left
            else:
                n = stack.pop(-1)
                if n != None:
                    root = n.right
        return  res
        '''    

猜你喜欢

转载自www.cnblogs.com/cheslee/p/13380131.html