美文网首页
Binary Tree Preorder Traversal

Binary Tree Preorder Traversal

作者: ab409 | 来源:发表于2015-12-03 19:24 被阅读119次

    Binary Tree Preorder Traversal


    今天是一道有关基础的题目,来自LeetCode,难度为Medium,Acceptance为37.8%

    题目如下


    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?

    解题思路及代码见阅读原文

    回复0000查看更多题目

    解题思路


    二叉树的前序,中序,后续遍历都是数据结构课程的基础了。

    不做过多解释了,大家权当回忆一下大学时代吧。

    代码如下


    Java版

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

    相关文章

      网友评论

          本文标题:Binary Tree Preorder Traversal

          本文链接:https://www.haomeiwen.com/subject/bmdshttx.html