/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
type StackNode struct {
Parr [1000]*TreeNode
Index int
}
func(s *StackNode) IsEmpty() bool {
if s.Index <= 0 {
return true
}else {
return false
}
}
func(s *StackNode) Push(p *TreeNode) {
s.Parr[s.Index] = p
s.Index = s.Index + 1
}
func(s *StackNode) Pop() (*TreeNode){
if s.Index > 0 {
s.Index = s.Index - 1
return s.Parr[s.Index]
}else {
return nil
}
}
type StackVal struct {
Parr [1000]int
Index int
}
func(s *StackVal) IsEmpty() bool {
if s.Index <= 0 {
return true
}else {
return false
}
}
func(s *StackVal) Push(p int) {
s.Parr[s.Index] = p
s.Index = s.Index + 1
}
func(s *StackVal) Pop() (int){
if s.Index > 0 {
s.Index = s.Index - 1
return s.Parr[s.Index]
}else {
return 0
}
}
func hasPathSum(root *TreeNode, targetSum int) bool {
if nil == root {
return false
}
stacknode := StackNode{}
stackval := StackVal{}
stacknode.Push(root)
stackval.Push(root.Val)
for ; !stacknode.IsEmpty(); {
curNode := stacknode.Pop()
curVal := stackval.Pop()
if curVal == targetSum && curNode.Left == nil && curNode.Right == nil {
return true
}
if curNode.Right != nil {
rightVal := curVal + curNode.Right.Val
stacknode.Push(curNode.Right)
stackval.Push(rightVal)
}
if curNode.Left != nil {
leftVal := curVal + curNode.Left.Val
stacknode.Push(curNode.Left)
stackval.Push(leftVal)
}
}
return false
}
leetcode面试题二叉树路径总和迭代实现
最新推荐文章于 2022-01-21 01:27:24 发布