首页 > 代码库 > Binary Tree Preorder Traversal

Binary Tree Preorder Traversal

https://oj.leetcode.com/problems/binary-tree-preorder-traversal/

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?

解题思路:

很简单,递归。

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

但原题提出不用递归的方法,即遍历。使用stack,遇到一个节点,首先list.add(root.val),如果左节点不为空,下移到左节点,同时如果右节点不为空,将右节点推入stack。如果左节点为空,从stack中弹出最上面的节点作为下一个节点,循环处理。直到stack为空,而且当前处理节点为空。

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

 

Binary Tree Preorder Traversal