Binary Tree Preorder Traversal

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 preorderTraversal(TreeNode root) {
        ArrayList list = new ArrayList();
            Stack stack = new Stack();
            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;
    }
}

关注我
该公众号会每天推送常见面试题,包括解题思路是代码,希望对找工作的同学有所帮助

image

你可能感兴趣的:(Binary Tree Preorder Traversal)