how to get the path from root to a given node on a binary tree?

后端 未结 5 1541
傲寒
傲寒 2020-12-23 22:29

I am trying to find out how to get the path from root to a given node on a binary tree.

It is not binary search tree.

Each non-leaf node has only two point

5条回答
  •  北海茫月
    2020-12-23 23:05

    public List> getPath(T data){
            Stack> stack = new Stack>();
            Boolean found =  getPath(root, stack, data);
            List> path = new ArrayList>();
    
            if(!found){
                return path;
            }
            return Arrays.asList(stack.toArray((Node[])new Node[stack.size()]));
        }
    
        public Boolean getPath(Node node, Stack> stack, T data){
            if(node == null){
                return false;
            }
            stack.push(node);
    
            if(node.data.equals(data)){
                return true;
            }
            Boolean found = getPath(node.left, stack, data) ||
                    getPath(node.right, stack, data);
    
            if(!found ){
                stack.pop();
            }
            return found;
        }
    

提交回复
热议问题