144. Binary Tree Preorder Traversal

来源:互联网 发布:java社区 编辑:程序博客网 时间:2024/06/15 23:26

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].

类似于中序遍历。

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



0 0
原创粉丝点击