DFS by golang


  • 0
    M

    Because language features, you can't simply use the existing data structure, you can only make one out of your own。

    /**
     * Definition for a binary tree node.
     * type TreeNode struct {
     *     Val int
     *     Left *TreeNode
     *     Right *TreeNode
     * }
     */
    
    //this works like list in java
    type ArrayInstance struct {
    	Array []int
    }
    
    func largestValues(root *TreeNode) []int {
        res := new(ArrayInstance)
        res.Array = make([]int, 0)
        
        dfs(root, res, 0)
        
        return res.Array
    }
    
    func dfs(root *TreeNode, res *ArrayInstance, row int) {
        if root == nil {
    		return
    	}
        
    	setMax(root, res, row)
    	dfs(root.Left, res, row + 1)
    	dfs(root.Right, res, row + 1)
    }
    
    func setMax(node *TreeNode, res *ArrayInstance, row int) {
    	if row >= len(res.Array) {
    		res.Array = append(res.Array, node.Val)
    	} else {
    		if res.Array[row] < node.Val {
    			res.Array[row] = node.Val
    		}
    	}
    }
    

    but still need 19ms, how to improve the efficiency of execution?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.