Iterative C# DFS Solution


  • 0
    P
        public class TreeNode
        {
            public int val;
            public int valtillnow;
            public TreeNode left;
            public TreeNode right;
            public TreeNode(int x, TreeNode left, TreeNode right) { val = x; this.left = left; this.right = right; }
    }
    
            public int dfs(TreeNode tn)
            {
                Stack<TreeNode> st = new Stack<TreeNode>();
                tn.valtillnow = tn.val;
                st.Push(tn);
                int sum = 0;
    
                while (st.Count != 0)
                {
                    TreeNode cur = st.Pop();
                    if (cur != null)
                    {
                        if (cur.left != null) { st.Push(cur.left); cur.left.valtillnow = cur.valtillnow + cur.left.val; }
                        if (cur.right != null) { st.Push(cur.right); cur.right.valtillnow = cur.valtillnow + cur.right.val; }
                        if (cur.left == null && cur.right == null)
                            sum += cur.valtillnow;
                    }
                }
                return sum;
    }

Log in to reply
 

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