LintCode 66. 二叉树的前序遍历

给出一棵二叉树,返回其节点值的前序遍历。

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
   /**
    * @param root: A Tree
    * @return: Preorder in ArrayList which contains node values.
    */
   public List<Integer> preorderTraversal(TreeNode root) {
      // write your code here
      List<Integer> list = new ArrayList<>();
      if (root != null) {
         list.add(root.val);
         find(root.left, list);
         find(root.right, list);
      }
      return list;
   }

   private void find(TreeNode treeNode, List<Integer> list) {
      if (treeNode != null) {
         list.add(treeNode.val);
         find(treeNode.left, list);
         find(treeNode.right, list);
      }
   }
}

阅读更多

没有更多推荐了,返回首页