二叉树的前,中,后序遍历

题意:

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

数据范围:二叉树的节点数量满足 0 \le n \le 100 \0≤n≤100  ,二叉树节点的值满足 1 \le val \le 100 \1≤val≤100  ,树的各节点的值各不相同

示例:

输入:

{1,#,2,3}

返回值:

[1,2,3]

题解:前序是根左右,中序是左根右,后序是左右根

1.递归写法

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @return int整型一维数组
     */
    public void pp(List<Integer> list,TreeNode t)
    {

        if(t==null)
            return ;
//前序
        list.add(t.val);
            pp(list,t.left);
        pp(list,t.right);
//中序
/*

            pp(list,t.left);  
         list.add(t.val);
        pp(list,t.right);

*/
//后序
/*
  pp(list,t.left);  
         
        pp(list,t.right);
             list.add(t.val);

*/
    }
    public int[] preorderTraversal (TreeNode root) {
        // write code here
        ArrayList<Integer> a=new ArrayList<>();
        pp(a,root);
        int [] num=new int[a.size()];
        for(int i=0;i<a.size();++i)
        {
            num[i]=a.get(i);
        }
        return num;
        
    }
}

2.非递归写法,是用栈模拟函数递归调用的过程。

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @return int整型一维数组
     */
  
    public int[] preorderTraversal (TreeNode root) {
        // write code here
        ArrayList<Integer> a=new ArrayList<>();
       Stack<TreeNode> stack=new Stack<>();
       if(root==null)
           return new int [0];
        stack.push(root);
//前序
        while(!stack.empty())
        {
            TreeNode t=stack.pop();
            a.add(t.val);
            if(t.right!=null)
            stack.push(t.right);
             if(t.left!=null)
            stack.push(t.left);
        } 
        int [] num=new int[a.size()];
        for(int i=0;i<a.size();++i)
        {
            num[i]=a.get(i);
        }
        return num;
        
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值