二叉树的前序遍历

此博客链接:https://www.cnblogs.com/ping2yingshi/p/14085288.html

二叉树的前序遍历

题目链接:https://leetcode-cn.com/problems/binary-tree-preorder-traversal/

题目

给你二叉树的根节点 root ,返回它节点值的 前序 遍历。

示例 1:


输入:root = [1,null,2,3]
输出:[1,2,3]
示例 2:

输入:root = []
输出:[]
示例 3:

输入:root = [1]
输出:[1]
示例 4:


输入:root = [1,2]
输出:[1,2]
示例 5:


输入:root = [1,null,2]
输出:[1,2]
 

提示:

树中节点数目在范围 [0, 100] 内
-100 <= Node.val <= 100 

题解

思路1:利用递归思想

前序遍历是先遍历根节点,然后遍历左子树,在遍历右子树,但是左子树中也可能是一个树结构,右子树中也可能是一个树结构,所以前序遍历是先遍历根节点,然后遍历左子树中的全部节点,再遍历右子树中的全部节点。可以使用递归进行前序遍历。

方法1:

          1.定义一个函数,传入根节点和前序遍历结果,递归调用根节点的左子树,右子树。

          2.判断边界条件,当根为空,说明么有节点,返回结果。

          

代码1

class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list=new ArrayList<Integer>();
        Pre(root,list);
        return list;
        
    }
    public void Pre(TreeNode root,List<Integer> list){
        if(root==null)
        {
           return ;
        }
        list.add(root.val);
        if(root.left!=null){
               Pre(root.left,list);
        }
         if(root.right!=null){
               Pre(root.right,list);
        }
    }
}

结果1

思路2:利用迭代思想

迭代遍历树,首先需要一个栈来存储节点,先把头节点放到栈中,然后出栈,把出栈的节点右子树加入到栈中,再把节点的左子树加入到栈中。然后在出栈,只要栈不为空,就一直进行以上操作,进栈出栈。

方法2

          1.定义一个栈,先把根节点入栈。

          2.把节点从栈中取出,加入到结果数组中。

          3.判断右子树是否为空,不为空把左子树加入栈中。

          4.判断左子树是否为空,不为空把右子树加入栈中。

代码2

class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        
        List<Integer> list=new ArrayList<Integer>();
        if(root==null)
        return list;
        Stack<TreeNode> stack=new Stack();
        stack.push(root);
        while(!stack.empty()){
            TreeNode temp=stack.pop();
            list.add(temp.val);
            if(temp.right!=null){
                stack.push(temp.right);
            }
            if(temp.left!=null){
                stack.push(temp.left);
            }
        }
        return list;
        
    }
   
}

结果2

 

原文地址:https://www.cnblogs.com/ping2yingshi/p/14085288.html