leetcode257 (all paths of a binary tree: binary tree search)

Given a binary tree, return all paths from the root node to the leaf nodes.
Explanation: A leaf node refers to a node without child nodes.

Example:
Input: [1,2,3,null,5]
Output: Output: ["1->2->5", "1->3"]

Solution: Adopt the DFS depth-first search method, use the stack to traverse, and the path is just saved in the stack, and whenever a leaf node is encountered, the existing elements in the stack are combined into a string path.

class Solution {
    
    
    public List<String> binaryTreePaths(TreeNode root) {
    
    
        /*
        * 用栈来保存路径,同时进行树的遍历,
        * 同时要注意的是栈中的每一个结点都有两次搜索机会
        * 当一次搜索得到结点的右孩子后,结点不出栈,而是存储在
        * 栈中,防止路径顺序被破环,直到从栈中提取的该结点,再弹出栈
        */
            Map<TreeNode,Integer>map=new HashMap<>();
            List<String>res=new ArrayList<>();
            Stack<TreeNode>stack=new Stack<>();
            TreeNode node=root;
            while (!stack.isEmpty() || node != null) {
    
    
                while (node != null) {
    
    
                    stack.push(node);
                    map.put(node,0);
                    if (node.left == null && node.right == null) {
    
    
                        res.add(getRoute(stack));
                    }
                    node = node.left;
                }
                node = stack.peek();
                int temp=map.get(node);
                if(temp==1) {
    
    
                    stack.pop();
                    node=null;
                }
                else {
    
    
                    map.put(node, 1);
                    node=node.right;
                }
            }
            return res;
    }
    private String getRoute(Stack<TreeNode>stack){
    
    
        StringBuilder route=new StringBuilder();
        for(TreeNode x:stack){
    
    
            route.append(x.val).append("->");
        }
        int len=route.length();
        route.delete(len-2,len);
        return route.toString();
    }
}

Guess you like

Origin blog.csdn.net/CY2333333/article/details/108397118