二叉树的前序遍历

给定一个二叉树,返回它的 前序 遍历。

 示例:

输入: [1,null,2,3]
1
\
2
/
3

输出: [1,2,3]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-preorder-traversal

递归实现:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if(root ==null) return list;
        help(root,list);
        return list;
    }
    public List<Integer> help(TreeNode node ,List<Integer> list){
        if(node==null )return list;
        list.add(node.val);
        help(node.left,list);
        help(node.right,list);
        return list;
    }
}

迭代实现:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<Integer>();
        Stack<TreeNode> stack = new Stack<>();
        if(root == null)
            return list;
        stack.push(root);
        while(!stack.isEmpty()){
            root = stack.pop();
            list.add(root.val);
            if(root.right != null)
                stack.push(root.right);
            if(root.left != null)
                stack.push(root.left);
        }
        
        return list; 
    }
}

但是相对与迭代实现,递归实现相对简单而且效率较高。

posted on 2020-08-04 17:18  九七97  阅读(225)  评论(0编辑  收藏  举报

导航