Leet-code144. Binary Tree Preorder Traversal

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leet-code144. Binary Tree Preorder Traversal相关的知识,希望对你有一定的参考价值。

这是一道将二叉树先序遍历,题目不难,采用深搜

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
   public static List<Integer> resultlist = new ArrayList<Integer>();

    public static void dfs (TreeNode root ,boolean flag ) {
        if(flag==true)
        {
            resultlist.clear();
        }
        if(root==null)
        {
            return ;
        }

            resultlist.add(root.val);

        if(root.left!=null)
        {
            dfs(root.left,false);
        }
        if(root.right!=null)
        {
            dfs(root.right,false);
        }
        
    }


    public static List<Integer> preorderTraversal(TreeNode root ) {
        dfs(root,true);
        return resultlist;
    }

}

 

以上是关于Leet-code144. Binary Tree Preorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章