leetcode记录 257. Binary Tree Paths

来源:互联网 发布:js div左右滑动效果 编辑:程序博客网 时间:2024/06/06 17:29
自己的思路:分析还是主要考察二叉树的遍历,遍历的时候判断是否为叶子节点,遍历的同时记录路径上值,如果为叶子节点那么输出路径。
                      路径上的值采用list来存储,有子结点的话,加入list,跳到其他节点(右节点)时候,删除list最后一个节点,就说当该节点被遍历过之后从path中删除该节点。
/** * 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<Integer> path = new ArrayList<Integer>();        List<String> rslt = new ArrayList<String>();        if(root==null)            return rslt;        treeTraverse(root,path,rslt);        return rslt;    }        public void treeTraverse(TreeNode root,List<Integer> path,List<String> rslt){        if(root!=null)            path.add(root.val);        if(root.left!=null){            treeTraverse(root.left,path,rslt);        }        if(root.right!=null){                        treeTraverse(root.right,path,rslt);        }        if(root.left==null&&root.right==null){            String entry = "";            for(int i=0;i<path.size();i++){                if(i!=0)                    entry+="->";                entry+=path.get(i);            }            rslt.add(entry);        }        path.remove(path.size()-1);    }}

其实根本都不用专门的一个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;        }        return getPaths (root, "", res);    }    public List<String> getPaths(TreeNode root, String str, List<String> res){        if (root.left == null && root.right == null){            if (str.equals("")){                str += root.val;            }            else {                str += "->"+root.val;            }            res.add (str);            return res;        }        if (str.equals("")){            str += root.val;        }        else {            str += "->"+root.val;        }        if (root.left != null){            getPaths (root.left, str, res);        }        if (root.right != null){            getPaths (root.right, str, res);        }        return res;    }}
以上路径保存在str中。


0 0
原创粉丝点击