【LeetCode】Binary Tree Preorder Traversal 解题报告

来源:互联网 发布:10月经济数据 统计局 编辑:程序博客网 时间:2024/06/07 17:43

【LeetCode】Binary Tree Preorder Traversal 解题报告

标签(空格分隔): LeetCode


题目地址:https://leetcode.com/problems/binary-tree-preorder-traversal/#/description

题目描述:

Given a binary tree, return the preorder traversal of its nodes’ values.

For example:
Given binary tree {1,#,2,3},

   1    \     2    /   3

return [1,2,3].

Note: Recursive solution is trivial, could you do it iteratively?

Ways

这个题就是最简单的先序遍历,先用递归的方法做了一遍。很简单。

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

然后非递归的:用栈,先把右孩子进栈,再左孩子进栈.

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

Date

2017 年 5 月 20 日

阅读全文
0 0
原创粉丝点击