zoukankan      html  css  js  c++  java
  • 257. Binary Tree Paths

    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * 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<String> binaryTreePaths(TreeNode root) {
            List<String> res=new ArrayList<String>();
            if(root==null)
                return res;
            List<Integer> temp=new ArrayList<Integer>();
            dfs(root,res,temp);
            return res;
        }
        
        public void dfs(TreeNode root,List<String> res,List<Integer> temp)
        {
            temp.add(root.val);
            if(root.left==null&&root.right==null)
            {
                //表示此时已经走到了叶子节点,直接进行temp的压入即可
                String newOne="";
                for(int i=0;i<temp.size();i++)
                {
                    if(i==0)
                        newOne+=temp.get(i);
                    else
                    {
                        newOne+="->";
                        newOne+=temp.get(i);
                    }
                }
                
                res.add(newOne);
                return ;
            }
            
            if(root.left!=null)
            {
                dfs(root.left,res,temp);
                temp.remove(temp.size()-1);
            }
            if(root.right!=null)
            {
                dfs(root.right,res,temp);
                temp.remove(temp.size()-1);
            }
            
        }
    }
  • 相关阅读:
    C++类中的函数重载
    C++中的友元
    bzoj 2820
    莫比乌斯函数
    bzoj 2440: [中山市选2011]完全平方数
    莫比乌斯反演1
    [转]C++ 指针和引用
    P2756 飞行员配对方案问题
    P2055 [ZJOI2009]假期的宿舍
    P2654 原核生物培养
  • 原文地址:https://www.cnblogs.com/aguai1992/p/5665721.html
Copyright © 2011-2022 走看看