print all root to leaf paths in a binary tree

后端 未结 12 1370
野性不改
野性不改 2020-12-23 14:55

i am trying to print all root to leaf paths in a binary tree using java.

public void printAllRootToLeafPaths(Node node,ArrayList path) 
{
    if(node==null)         


        
12条回答
  •  甜味超标
    2020-12-23 15:41

    It is written with JS but You can gain the logic.

    function dive(t, res, arr) {
            if(t.value != null && t.value != undefined) {
                res = res ? `${res}->${t.value}`: `${t.value}`;
            }
            if(t.left) {
                dive(t.left, res, arr );
            } 
            if(t.right) {
                dive(t.right, res, arr );
            } 
            if(!t.left && !t.right) {
                console.log(res)
                arr.push(res);
                return;
            }
    }
    
    function getPaths(t) {
        let arr = [];
        if(!t.left && !t.right) {
            t.value != null && t.value != undefined && arr.push(`${t.value}`);
            console.log(arr)
            return arr;
        }
        dive(t, null, arr);
        console.log(arr)
    }
    
    
    //INPUT
    const x = {
        value: 5,
        left: {
            value: 4,
            left: {
                value: 3,
                left: {
                    value: 2,
                    left: {
                        value: 1,
                        left: {
                            value: 0
                        },
                        right: {
                            value: 1.5
                        }
                    },
                    right: {
                        value: 2.5
                    }
                },
                right: {
                    value: 3.5
                }
            },
            right: {
                value: 4.5,
                right: {
                    value: 4.8
                }
            }
        },
        right: {
            value: 8,
            left: {
                value: 7
            }
        }
    }
    
    getPaths(x);
    
    //OUTPUT
    
    [ '5->4->3->2->1->0',
      '5->4->3->2->1->1.5',
      '5->4->3->2->2.5',
      '5->4->3->3.5',
      '5->4->4.5->4.8',
      '5->8->7' ]
    
    

提交回复
热议问题